blob: e56569dc6c77ba53bffa3559301232e52146b128 [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();
66 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
68 // this actually matters for arrays of unknown bound. Using the type of
69 // the most recent declaration isn't clearly correct in general. Eg:
70 //
71 // extern int arr[]; void f() { extern int arr[3]; };
72 // constexpr int *p = &arr[1]; // valid?
73 return cast<ValueDecl>(D->getMostRecentDecl())->getType();
Richard Smith84401042013-06-03 05:03:02 +000074
75 const Expr *Base = B.get<const Expr*>();
76
77 // For a materialized temporary, the type of the temporary we materialized
78 // may not be the type of the expression.
79 if (const MaterializeTemporaryExpr *MTE =
80 dyn_cast<MaterializeTemporaryExpr>(Base)) {
81 SmallVector<const Expr *, 2> CommaLHSs;
82 SmallVector<SubobjectAdjustment, 2> Adjustments;
83 const Expr *Temp = MTE->GetTemporaryExpr();
84 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
85 Adjustments);
86 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000087 // for it directly. Otherwise use the type after adjustment.
88 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000089 return Inner->getType();
90 }
91
92 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000093 }
94
Richard Smithd62306a2011-11-10 06:34:14 +000095 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000096 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000097 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000098 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000099 APValue::BaseOrMemberType Value;
100 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +0000101 return Value;
102 }
103
104 /// Get an LValue path entry, which is known to not be an array index, as a
105 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000106 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000107 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000108 }
109 /// Get an LValue path entry, which is known to not be an array index, as a
110 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000111 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000112 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000113 }
114 /// Determine whether this LValue path entry for a base class names a virtual
115 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000116 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000117 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000118 }
119
George Burgess IVe3763372016-12-22 02:50:20 +0000120 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
121 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
122 const FunctionDecl *Callee = CE->getDirectCallee();
123 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
124 }
125
126 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
127 /// This will look through a single cast.
128 ///
129 /// Returns null if we couldn't unwrap a function with alloc_size.
130 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
131 if (!E->getType()->isPointerType())
132 return nullptr;
133
134 E = E->IgnoreParens();
135 // If we're doing a variable assignment from e.g. malloc(N), there will
136 // probably be a cast of some kind. Ignore it.
137 if (const auto *Cast = dyn_cast<CastExpr>(E))
138 E = Cast->getSubExpr()->IgnoreParens();
139
140 if (const auto *CE = dyn_cast<CallExpr>(E))
141 return getAllocSizeAttr(CE) ? CE : nullptr;
142 return nullptr;
143 }
144
145 /// Determines whether or not the given Base contains a call to a function
146 /// with the alloc_size attribute.
147 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
148 const auto *E = Base.dyn_cast<const Expr *>();
149 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
150 }
151
Richard Smith6f4f0f12017-10-20 22:56:25 +0000152 /// The bound to claim that an array of unknown bound has.
153 /// The value in MostDerivedArraySize is undefined in this case. So, set it
154 /// to an arbitrary value that's likely to loudly break things if it's used.
155 static const uint64_t AssumedSizeForUnsizedArray =
156 std::numeric_limits<uint64_t>::max() / 2;
157
George Burgess IVe3763372016-12-22 02:50:20 +0000158 /// Determines if an LValue with the given LValueBase will have an unsized
159 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000160 /// Find the path length and type of the most-derived subobject in the given
161 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000162 static unsigned
163 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
164 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000165 uint64_t &ArraySize, QualType &Type, bool &IsArray,
166 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000167 // This only accepts LValueBases from APValues, and APValues don't support
168 // arrays that lack size info.
169 assert(!isBaseAnAllocSizeCall(Base) &&
170 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000171 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000172 Type = getType(Base);
173
Richard Smith80815602011-11-07 05:07:52 +0000174 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000175 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000176 const ArrayType *AT = Ctx.getAsArrayType(Type);
177 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000178 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000179 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000180
181 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
182 ArraySize = CAT->getSize().getZExtValue();
183 } else {
184 assert(I == 0 && "unexpected unsized array designator");
185 FirstEntryIsUnsizedArray = true;
186 ArraySize = AssumedSizeForUnsizedArray;
187 }
Richard Smith66c96992012-02-18 22:04:06 +0000188 } else if (Type->isAnyComplexType()) {
189 const ComplexType *CT = Type->castAs<ComplexType>();
190 Type = CT->getElementType();
191 ArraySize = 2;
192 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000193 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000194 } else if (const FieldDecl *FD = getAsField(Path[I])) {
195 Type = FD->getType();
196 ArraySize = 0;
197 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000198 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000199 } else {
Richard Smith80815602011-11-07 05:07:52 +0000200 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000201 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000202 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000203 }
Richard Smith80815602011-11-07 05:07:52 +0000204 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000205 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000206 }
207
Richard Smitha8105bc2012-01-06 16:39:00 +0000208 // The order of this enum is important for diagnostics.
209 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000210 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000211 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000212 };
213
Richard Smith96e0c102011-11-04 02:25:55 +0000214 /// A path from a glvalue to a subobject of that glvalue.
215 struct SubobjectDesignator {
216 /// True if the subobject was named in a manner not supported by C++11. Such
217 /// lvalues can still be folded, but they are not core constant expressions
218 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000219 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000220
Richard Smitha8105bc2012-01-06 16:39:00 +0000221 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000222 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000223
Daniel Jasperffdee092017-05-02 19:21:42 +0000224 /// Indicator of whether the first entry is an unsized array.
225 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000226
George Burgess IVa51c4072015-10-16 01:49:01 +0000227 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000228 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000229
Richard Smitha8105bc2012-01-06 16:39:00 +0000230 /// The length of the path to the most-derived object of which this is a
231 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000232 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000233
George Burgess IVa51c4072015-10-16 01:49:01 +0000234 /// The size of the array of which the most-derived object is an element.
235 /// This will always be 0 if the most-derived object is not an array
236 /// element. 0 is not an indicator of whether or not the most-derived object
237 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000238 ///
239 /// If the current array is an unsized array, the value of this is
240 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000241 uint64_t MostDerivedArraySize;
242
243 /// The type of the most derived object referred to by this address.
244 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000245
Richard Smith80815602011-11-07 05:07:52 +0000246 typedef APValue::LValuePathEntry PathEntry;
247
Richard Smith96e0c102011-11-04 02:25:55 +0000248 /// The entries on the path from the glvalue to the designated subobject.
249 SmallVector<PathEntry, 8> Entries;
250
Richard Smitha8105bc2012-01-06 16:39:00 +0000251 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000252
Richard Smitha8105bc2012-01-06 16:39:00 +0000253 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000254 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000255 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000256 MostDerivedPathLength(0), MostDerivedArraySize(0),
257 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000258
259 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000260 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000261 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000262 MostDerivedPathLength(0), MostDerivedArraySize(0) {
263 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000264 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000265 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000266 ArrayRef<PathEntry> VEntries = V.getLValuePath();
267 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000268 if (V.getLValueBase()) {
269 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000270 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000271 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000272 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000273 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000274 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000275 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000276 }
Richard Smith80815602011-11-07 05:07:52 +0000277 }
278 }
279
Richard Smith96e0c102011-11-04 02:25:55 +0000280 void setInvalid() {
281 Invalid = true;
282 Entries.clear();
283 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000284
George Burgess IVe3763372016-12-22 02:50:20 +0000285 /// Determine whether the most derived subobject is an array without a
286 /// known bound.
287 bool isMostDerivedAnUnsizedArray() const {
288 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000289 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000290 }
291
292 /// Determine what the most derived array's size is. Results in an assertion
293 /// failure if the most derived array lacks a size.
294 uint64_t getMostDerivedArraySize() const {
295 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
296 return MostDerivedArraySize;
297 }
298
Richard Smitha8105bc2012-01-06 16:39:00 +0000299 /// Determine whether this is a one-past-the-end pointer.
300 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000301 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000302 if (IsOnePastTheEnd)
303 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000304 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000305 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
306 return true;
307 return false;
308 }
309
310 /// Check that this refers to a valid subobject.
311 bool isValidSubobject() const {
312 if (Invalid)
313 return false;
314 return !isOnePastTheEnd();
315 }
316 /// Check that this refers to a valid subobject, and if not, produce a
317 /// relevant diagnostic and set the designator as invalid.
318 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
319
320 /// Update this designator to refer to the first element within this array.
321 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000322 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000323 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000324 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000325
326 // This is a most-derived object.
327 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000328 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000329 MostDerivedArraySize = CAT->getSize().getZExtValue();
330 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000331 }
George Burgess IVe3763372016-12-22 02:50:20 +0000332 /// Update this designator to refer to the first element within the array of
333 /// elements of type T. This is an array of unknown size.
334 void addUnsizedArrayUnchecked(QualType ElemTy) {
335 PathEntry Entry;
336 Entry.ArrayIndex = 0;
337 Entries.push_back(Entry);
338
339 MostDerivedType = ElemTy;
340 MostDerivedIsArrayElement = true;
341 // The value in MostDerivedArraySize is undefined in this case. So, set it
342 // to an arbitrary value that's likely to loudly break things if it's
343 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000344 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000345 MostDerivedPathLength = Entries.size();
346 }
Richard Smith96e0c102011-11-04 02:25:55 +0000347 /// Update this designator to refer to the given base or member of this
348 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000349 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000350 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000351 APValue::BaseOrMemberType Value(D, Virtual);
352 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000353 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000354
355 // If this isn't a base class, it's a new most-derived object.
356 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
357 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000358 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000359 MostDerivedArraySize = 0;
360 MostDerivedPathLength = Entries.size();
361 }
Richard Smith96e0c102011-11-04 02:25:55 +0000362 }
Richard Smith66c96992012-02-18 22:04:06 +0000363 /// Update this designator to refer to the given complex component.
364 void addComplexUnchecked(QualType EltTy, bool Imag) {
365 PathEntry Entry;
366 Entry.ArrayIndex = Imag;
367 Entries.push_back(Entry);
368
369 // This is technically a most-derived object, though in practice this
370 // is unlikely to matter.
371 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000372 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000373 MostDerivedArraySize = 2;
374 MostDerivedPathLength = Entries.size();
375 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000376 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000377 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
378 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000379 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000380 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
381 if (Invalid || !N) return;
382 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
383 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000384 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000385 // Can't verify -- trust that the user is doing the right thing (or if
386 // not, trust that the caller will catch the bad behavior).
387 // FIXME: Should we reject if this overflows, at least?
388 Entries.back().ArrayIndex += TruncatedN;
389 return;
390 }
391
392 // [expr.add]p4: For the purposes of these operators, a pointer to a
393 // nonarray object behaves the same as a pointer to the first element of
394 // an array of length one with the type of the object as its element type.
395 bool IsArray = MostDerivedPathLength == Entries.size() &&
396 MostDerivedIsArrayElement;
397 uint64_t ArrayIndex =
398 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
399 uint64_t ArraySize =
400 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
401
402 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
403 // Calculate the actual index in a wide enough type, so we can include
404 // it in the note.
405 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
406 (llvm::APInt&)N += ArrayIndex;
407 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
408 diagnosePointerArithmetic(Info, E, N);
409 setInvalid();
410 return;
411 }
412
413 ArrayIndex += TruncatedN;
414 assert(ArrayIndex <= ArraySize &&
415 "bounds check succeeded for out-of-bounds index");
416
417 if (IsArray)
418 Entries.back().ArrayIndex = ArrayIndex;
419 else
420 IsOnePastTheEnd = (ArrayIndex != 0);
421 }
Richard Smith96e0c102011-11-04 02:25:55 +0000422 };
423
Richard Smith254a73d2011-10-28 22:34:42 +0000424 /// A stack frame in the constexpr call stack.
425 struct CallStackFrame {
426 EvalInfo &Info;
427
428 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000429 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000430
Richard Smithf6f003a2011-12-16 19:06:07 +0000431 /// Callee - The function which was called.
432 const FunctionDecl *Callee;
433
Richard Smithd62306a2011-11-10 06:34:14 +0000434 /// This - The binding for the this pointer in this call, if any.
435 const LValue *This;
436
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000437 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000438 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000439 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000440
Eli Friedman4830ec82012-06-25 21:21:08 +0000441 // Note that we intentionally use std::map here so that references to
442 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000443 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000444 typedef MapTy::const_iterator temp_iterator;
445 /// Temporaries - Temporary lvalues materialized within this stack frame.
446 MapTy Temporaries;
447
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000448 /// CallLoc - The location of the call expression for this call.
449 SourceLocation CallLoc;
450
451 /// Index - The call index of this call.
452 unsigned Index;
453
Faisal Vali051e3a22017-02-16 04:12:21 +0000454 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
455 // on the overall stack usage of deeply-recursing constexpr evaluataions.
456 // (We should cache this map rather than recomputing it repeatedly.)
457 // But let's try this and see how it goes; we can look into caching the map
458 // as a later change.
459
460 /// LambdaCaptureFields - Mapping from captured variables/this to
461 /// corresponding data members in the closure class.
462 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
463 FieldDecl *LambdaThisCaptureField;
464
Richard Smithf6f003a2011-12-16 19:06:07 +0000465 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
466 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000467 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000468 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000469
470 APValue *getTemporary(const void *Key) {
471 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000472 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000473 }
474 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000475 };
476
Richard Smith852c9db2013-04-20 22:23:05 +0000477 /// Temporarily override 'this'.
478 class ThisOverrideRAII {
479 public:
480 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
481 : Frame(Frame), OldThis(Frame.This) {
482 if (Enable)
483 Frame.This = NewThis;
484 }
485 ~ThisOverrideRAII() {
486 Frame.This = OldThis;
487 }
488 private:
489 CallStackFrame &Frame;
490 const LValue *OldThis;
491 };
492
Richard Smith92b1ce02011-12-12 09:28:41 +0000493 /// A partial diagnostic which we might know in advance that we are not going
494 /// to emit.
495 class OptionalDiagnostic {
496 PartialDiagnostic *Diag;
497
498 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000499 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
500 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000501
502 template<typename T>
503 OptionalDiagnostic &operator<<(const T &v) {
504 if (Diag)
505 *Diag << v;
506 return *this;
507 }
Richard Smithfe800032012-01-31 04:08:20 +0000508
509 OptionalDiagnostic &operator<<(const APSInt &I) {
510 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000511 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000512 I.toString(Buffer);
513 *Diag << StringRef(Buffer.data(), Buffer.size());
514 }
515 return *this;
516 }
517
518 OptionalDiagnostic &operator<<(const APFloat &F) {
519 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000520 // FIXME: Force the precision of the source value down so we don't
521 // print digits which are usually useless (we don't really care here if
522 // we truncate a digit by accident in edge cases). Ideally,
Daniel Jasperffdee092017-05-02 19:21:42 +0000523 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000524 // representation which rounds to the correct value, but it's a bit
525 // tricky to implement.
526 unsigned precision =
527 llvm::APFloat::semanticsPrecision(F.getSemantics());
528 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000529 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000530 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000531 *Diag << StringRef(Buffer.data(), Buffer.size());
532 }
533 return *this;
534 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000535 };
536
Richard Smith08d6a2c2013-07-24 07:11:57 +0000537 /// A cleanup, and a flag indicating whether it is lifetime-extended.
538 class Cleanup {
539 llvm::PointerIntPair<APValue*, 1, bool> Value;
540
541 public:
542 Cleanup(APValue *Val, bool IsLifetimeExtended)
543 : Value(Val, IsLifetimeExtended) {}
544
545 bool isLifetimeExtended() const { return Value.getInt(); }
546 void endLifetime() {
547 *Value.getPointer() = APValue();
548 }
549 };
550
Richard Smithb228a862012-02-15 02:18:13 +0000551 /// EvalInfo - This is a private struct used by the evaluator to capture
552 /// information about a subexpression as it is folded. It retains information
553 /// about the AST context, but also maintains information about the folded
554 /// expression.
555 ///
556 /// If an expression could be evaluated, it is still possible it is not a C
557 /// "integer constant expression" or constant expression. If not, this struct
558 /// captures information about how and why not.
559 ///
560 /// One bit of information passed *into* the request for constant folding
561 /// indicates whether the subexpression is "evaluated" or not according to C
562 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
563 /// evaluate the expression regardless of what the RHS is, but C only allows
564 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000565 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000566 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000567
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000568 /// EvalStatus - Contains information about the evaluation.
569 Expr::EvalStatus &EvalStatus;
570
571 /// CurrentCall - The top of the constexpr call stack.
572 CallStackFrame *CurrentCall;
573
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000574 /// CallStackDepth - The number of calls in the call stack right now.
575 unsigned CallStackDepth;
576
Richard Smithb228a862012-02-15 02:18:13 +0000577 /// NextCallIndex - The next call index to assign.
578 unsigned NextCallIndex;
579
Richard Smitha3d3bd22013-05-08 02:12:03 +0000580 /// StepsLeft - The remaining number of evaluation steps we're permitted
581 /// to perform. This is essentially a limit for the number of statements
582 /// we will evaluate.
583 unsigned StepsLeft;
584
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000585 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000586 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000587 CallStackFrame BottomFrame;
588
Richard Smith08d6a2c2013-07-24 07:11:57 +0000589 /// A stack of values whose lifetimes end at the end of some surrounding
590 /// evaluation frame.
591 llvm::SmallVector<Cleanup, 16> CleanupStack;
592
Richard Smithd62306a2011-11-10 06:34:14 +0000593 /// EvaluatingDecl - This is the declaration whose initializer is being
594 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000595 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000596
597 /// EvaluatingDeclValue - This is the value being constructed for the
598 /// declaration whose initializer is being evaluated, if any.
599 APValue *EvaluatingDeclValue;
600
Erik Pilkington42925492017-10-04 00:18:55 +0000601 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
602 /// the call index that that lvalue was allocated in.
603 typedef std::pair<APValue::LValueBase, unsigned> EvaluatingObject;
604
605 /// EvaluatingConstructors - Set of objects that are currently being
606 /// constructed.
607 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
608
609 struct EvaluatingConstructorRAII {
610 EvalInfo &EI;
611 EvaluatingObject Object;
612 bool DidInsert;
613 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
614 : EI(EI), Object(Object) {
615 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
616 }
617 ~EvaluatingConstructorRAII() {
618 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
619 }
620 };
621
622 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex) {
623 return EvaluatingConstructors.count(EvaluatingObject(Decl, CallIndex));
624 }
625
Richard Smith410306b2016-12-12 02:53:20 +0000626 /// The current array initialization index, if we're performing array
627 /// initialization.
628 uint64_t ArrayInitIndex = -1;
629
Richard Smith357362d2011-12-13 06:39:58 +0000630 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
631 /// notes attached to it will also be stored, otherwise they will not be.
632 bool HasActiveDiagnostic;
633
Richard Smith0c6124b2015-12-03 01:36:22 +0000634 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
635 /// fold (not just why it's not strictly a constant expression)?
636 bool HasFoldFailureDiagnostic;
637
George Burgess IV8c892b52016-05-25 22:31:54 +0000638 /// \brief Whether or not we're currently speculatively evaluating.
639 bool IsSpeculativelyEvaluating;
640
Richard Smith6d4c6582013-11-05 22:18:15 +0000641 enum EvaluationMode {
642 /// Evaluate as a constant expression. Stop if we find that the expression
643 /// is not a constant expression.
644 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000645
Richard Smith6d4c6582013-11-05 22:18:15 +0000646 /// Evaluate as a potential constant expression. Keep going if we hit a
647 /// construct that we can't evaluate yet (because we don't yet know the
648 /// value of something) but stop if we hit something that could never be
649 /// a constant expression.
650 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000651
Richard Smith6d4c6582013-11-05 22:18:15 +0000652 /// Fold the expression to a constant. Stop if we hit a side-effect that
653 /// we can't model.
654 EM_ConstantFold,
655
656 /// Evaluate the expression looking for integer overflow and similar
657 /// issues. Don't worry about side-effects, and try to visit all
658 /// subexpressions.
659 EM_EvaluateForOverflow,
660
661 /// Evaluate in any way we know how. Don't worry about side-effects that
662 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000663 EM_IgnoreSideEffects,
664
665 /// Evaluate as a constant expression. Stop if we find that the expression
666 /// is not a constant expression. Some expressions can be retried in the
667 /// optimizer if we don't constant fold them here, but in an unevaluated
668 /// context we try to fold them immediately since the optimizer never
669 /// gets a chance to look at it.
670 EM_ConstantExpressionUnevaluated,
671
672 /// Evaluate as a potential constant expression. Keep going if we hit a
673 /// construct that we can't evaluate yet (because we don't yet know the
674 /// value of something) but stop if we hit something that could never be
675 /// a constant expression. Some expressions can be retried in the
676 /// optimizer if we don't constant fold them here, but in an unevaluated
677 /// context we try to fold them immediately since the optimizer never
678 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000679 EM_PotentialConstantExpressionUnevaluated,
680
George Burgess IVf9013bf2017-02-10 22:52:29 +0000681 /// Evaluate as a constant expression. In certain scenarios, if:
682 /// - we find a MemberExpr with a base that can't be evaluated, or
683 /// - we find a variable initialized with a call to a function that has
684 /// the alloc_size attribute on it
685 /// then we may consider evaluation to have succeeded.
686 ///
George Burgess IVe3763372016-12-22 02:50:20 +0000687 /// In either case, the LValue returned shall have an invalid base; in the
688 /// former, the base will be the invalid MemberExpr, in the latter, the
689 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
690 /// said CallExpr.
691 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000692 } EvalMode;
693
694 /// Are we checking whether the expression is a potential constant
695 /// expression?
696 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000697 return EvalMode == EM_PotentialConstantExpression ||
698 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000699 }
700
701 /// Are we checking an expression for overflow?
702 // FIXME: We should check for any kind of undefined or suspicious behavior
703 // in such constructs, not just overflow.
704 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
705
706 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000707 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000708 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000709 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000710 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
711 EvaluatingDecl((const ValueDecl *)nullptr),
712 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000713 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
714 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000715
Richard Smith7525ff62013-05-09 07:14:00 +0000716 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
717 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000718 EvaluatingDeclValue = &Value;
Erik Pilkington42925492017-10-04 00:18:55 +0000719 EvaluatingConstructors.insert({Base, 0});
Richard Smithd62306a2011-11-10 06:34:14 +0000720 }
721
David Blaikiebbafb8a2012-03-11 07:00:24 +0000722 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000723
Richard Smith357362d2011-12-13 06:39:58 +0000724 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000725 // Don't perform any constexpr calls (other than the call we're checking)
726 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000727 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000728 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000729 if (NextCallIndex == 0) {
730 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000731 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000732 return false;
733 }
Richard Smith357362d2011-12-13 06:39:58 +0000734 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
735 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000736 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000737 << getLangOpts().ConstexprCallDepth;
738 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000739 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000740
Richard Smithb228a862012-02-15 02:18:13 +0000741 CallStackFrame *getCallFrame(unsigned CallIndex) {
742 assert(CallIndex && "no call index in getCallFrame");
743 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
744 // be null in this loop.
745 CallStackFrame *Frame = CurrentCall;
746 while (Frame->Index > CallIndex)
747 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000748 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000749 }
750
Richard Smitha3d3bd22013-05-08 02:12:03 +0000751 bool nextStep(const Stmt *S) {
752 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000753 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000754 return false;
755 }
756 --StepsLeft;
757 return true;
758 }
759
Richard Smith357362d2011-12-13 06:39:58 +0000760 private:
761 /// Add a diagnostic to the diagnostics list.
762 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
763 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
764 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
765 return EvalStatus.Diag->back().second;
766 }
767
Richard Smithf6f003a2011-12-16 19:06:07 +0000768 /// Add notes containing a call stack to the current point of evaluation.
769 void addCallStack(unsigned Limit);
770
Faisal Valie690b7a2016-07-02 22:34:24 +0000771 private:
772 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
773 unsigned ExtraNotes, bool IsCCEDiag) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000774
Richard Smith92b1ce02011-12-12 09:28:41 +0000775 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000776 // If we have a prior diagnostic, it will be noting that the expression
777 // isn't a constant expression. This diagnostic is more important,
778 // unless we require this evaluation to produce a constant expression.
779 //
780 // FIXME: We might want to show both diagnostics to the user in
781 // EM_ConstantFold mode.
782 if (!EvalStatus.Diag->empty()) {
783 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000784 case EM_ConstantFold:
785 case EM_IgnoreSideEffects:
786 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000787 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000788 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000789 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000790 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000791 case EM_ConstantExpression:
792 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000793 case EM_ConstantExpressionUnevaluated:
794 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000795 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000796 HasActiveDiagnostic = false;
797 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000798 }
799 }
800
Richard Smithf6f003a2011-12-16 19:06:07 +0000801 unsigned CallStackNotes = CallStackDepth - 1;
802 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
803 if (Limit)
804 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000805 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000806 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000807
Richard Smith357362d2011-12-13 06:39:58 +0000808 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000809 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000810 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000811 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
812 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000813 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000814 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000815 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000816 }
Richard Smith357362d2011-12-13 06:39:58 +0000817 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000818 return OptionalDiagnostic();
819 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000820 public:
821 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
822 OptionalDiagnostic
823 FFDiag(SourceLocation Loc,
824 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
825 unsigned ExtraNotes = 0) {
826 return Diag(Loc, DiagId, ExtraNotes, false);
827 }
Daniel Jasperffdee092017-05-02 19:21:42 +0000828
Faisal Valie690b7a2016-07-02 22:34:24 +0000829 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000830 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000831 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000832 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000833 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000834 HasActiveDiagnostic = false;
835 return OptionalDiagnostic();
836 }
837
Richard Smith92b1ce02011-12-12 09:28:41 +0000838 /// Diagnose that the evaluation does not produce a C++11 core constant
839 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000840 ///
841 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
842 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000843 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000844 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000845 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000846 // Don't override a previous diagnostic. Don't bother collecting
847 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000848 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000849 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000850 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000851 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000852 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000853 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000854 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
855 = diag::note_invalid_subexpr_in_const_expr,
856 unsigned ExtraNotes = 0) {
857 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
858 }
Richard Smith357362d2011-12-13 06:39:58 +0000859 /// Add a note to a prior diagnostic.
860 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
861 if (!HasActiveDiagnostic)
862 return OptionalDiagnostic();
863 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000864 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000865
866 /// Add a stack of notes to a prior diagnostic.
867 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
868 if (HasActiveDiagnostic) {
869 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
870 Diags.begin(), Diags.end());
871 }
872 }
Richard Smith253c2a32012-01-27 01:14:48 +0000873
Richard Smith6d4c6582013-11-05 22:18:15 +0000874 /// Should we continue evaluation after encountering a side-effect that we
875 /// couldn't model?
876 bool keepEvaluatingAfterSideEffect() {
877 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000878 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000879 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000880 case EM_EvaluateForOverflow:
881 case EM_IgnoreSideEffects:
882 return true;
883
Richard Smith6d4c6582013-11-05 22:18:15 +0000884 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000885 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000886 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000887 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000888 return false;
889 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000890 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000891 }
892
893 /// Note that we have had a side-effect, and determine whether we should
894 /// keep evaluating.
895 bool noteSideEffect() {
896 EvalStatus.HasSideEffects = true;
897 return keepEvaluatingAfterSideEffect();
898 }
899
Richard Smithce8eca52015-12-08 03:21:47 +0000900 /// Should we continue evaluation after encountering undefined behavior?
901 bool keepEvaluatingAfterUndefinedBehavior() {
902 switch (EvalMode) {
903 case EM_EvaluateForOverflow:
904 case EM_IgnoreSideEffects:
905 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000906 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000907 return true;
908
909 case EM_PotentialConstantExpression:
910 case EM_PotentialConstantExpressionUnevaluated:
911 case EM_ConstantExpression:
912 case EM_ConstantExpressionUnevaluated:
913 return false;
914 }
915 llvm_unreachable("Missed EvalMode case");
916 }
917
918 /// Note that we hit something that was technically undefined behavior, but
919 /// that we can evaluate past it (such as signed overflow or floating-point
920 /// division by zero.)
921 bool noteUndefinedBehavior() {
922 EvalStatus.HasUndefinedBehavior = true;
923 return keepEvaluatingAfterUndefinedBehavior();
924 }
925
Richard Smith253c2a32012-01-27 01:14:48 +0000926 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000927 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000928 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000929 if (!StepsLeft)
930 return false;
931
932 switch (EvalMode) {
933 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 return true;
937
938 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000939 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000940 case EM_ConstantFold:
941 case EM_IgnoreSideEffects:
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 Smith253c2a32012-01-27 01:14:48 +0000946 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000947
George Burgess IV8c892b52016-05-25 22:31:54 +0000948 /// Notes that we failed to evaluate an expression that other expressions
949 /// directly depend on, and determine if we should keep evaluating. This
950 /// should only be called if we actually intend to keep evaluating.
951 ///
952 /// Call noteSideEffect() instead if we may be able to ignore the value that
953 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
954 ///
955 /// (Foo(), 1) // use noteSideEffect
956 /// (Foo() || true) // use noteSideEffect
957 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000958 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000959 // Failure when evaluating some expression often means there is some
960 // subexpression whose evaluation was skipped. Therefore, (because we
961 // don't track whether we skipped an expression when unwinding after an
962 // evaluation failure) every evaluation failure that bubbles up from a
963 // subexpression implies that a side-effect has potentially happened. We
964 // skip setting the HasSideEffects flag to true until we decide to
965 // continue evaluating after that point, which happens here.
966 bool KeepGoing = keepEvaluatingAfterFailure();
967 EvalStatus.HasSideEffects |= KeepGoing;
968 return KeepGoing;
969 }
970
Richard Smith410306b2016-12-12 02:53:20 +0000971 class ArrayInitLoopIndex {
972 EvalInfo &Info;
973 uint64_t OuterIndex;
974
975 public:
976 ArrayInitLoopIndex(EvalInfo &Info)
977 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
978 Info.ArrayInitIndex = 0;
979 }
980 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
981
982 operator uint64_t&() { return Info.ArrayInitIndex; }
983 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000984 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000985
986 /// Object used to treat all foldable expressions as constant expressions.
987 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000988 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000989 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000990 bool HadNoPriorDiags;
991 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000992
Richard Smith6d4c6582013-11-05 22:18:15 +0000993 explicit FoldConstant(EvalInfo &Info, bool Enabled)
994 : Info(Info),
995 Enabled(Enabled),
996 HadNoPriorDiags(Info.EvalStatus.Diag &&
997 Info.EvalStatus.Diag->empty() &&
998 !Info.EvalStatus.HasSideEffects),
999 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001000 if (Enabled &&
1001 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1002 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001003 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001004 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001005 void keepDiagnostics() { Enabled = false; }
1006 ~FoldConstant() {
1007 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001008 !Info.EvalStatus.HasSideEffects)
1009 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001010 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001011 }
1012 };
Richard Smith17100ba2012-02-16 02:46:34 +00001013
George Burgess IV3a03fab2015-09-04 21:28:13 +00001014 /// RAII object used to treat the current evaluation as the correct pointer
1015 /// offset fold for the current EvalMode
1016 struct FoldOffsetRAII {
1017 EvalInfo &Info;
1018 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +00001019 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001020 : Info(Info), OldMode(Info.EvalMode) {
1021 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +00001022 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001023 }
1024
1025 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1026 };
1027
George Burgess IV8c892b52016-05-25 22:31:54 +00001028 /// RAII object used to optionally suppress diagnostics and side-effects from
1029 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001030 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001031 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001032 Expr::EvalStatus OldStatus;
1033 bool OldIsSpeculativelyEvaluating;
Richard Smith17100ba2012-02-16 02:46:34 +00001034
George Burgess IV8c892b52016-05-25 22:31:54 +00001035 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001036 Info = Other.Info;
1037 OldStatus = Other.OldStatus;
Daniel Jaspera7e061f2017-08-17 06:33:46 +00001038 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001039 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001040 }
1041
1042 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001043 if (!Info)
1044 return;
1045
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001046 Info->EvalStatus = OldStatus;
1047 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
George Burgess IV8c892b52016-05-25 22:31:54 +00001048 }
1049
Richard Smith17100ba2012-02-16 02:46:34 +00001050 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001051 SpeculativeEvaluationRAII() = default;
1052
1053 SpeculativeEvaluationRAII(
1054 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001055 : Info(&Info), OldStatus(Info.EvalStatus),
1056 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
Richard Smith17100ba2012-02-16 02:46:34 +00001057 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001058 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001059 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001060
1061 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1062 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1063 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001064 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001065
1066 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1067 maybeRestoreState();
1068 moveFromAndCancel(std::move(Other));
1069 return *this;
1070 }
1071
1072 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001073 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001074
1075 /// RAII object wrapping a full-expression or block scope, and handling
1076 /// the ending of the lifetime of temporaries created within it.
1077 template<bool IsFullExpression>
1078 class ScopeRAII {
1079 EvalInfo &Info;
1080 unsigned OldStackSize;
1081 public:
1082 ScopeRAII(EvalInfo &Info)
1083 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1084 ~ScopeRAII() {
1085 // Body moved to a static method to encourage the compiler to inline away
1086 // instances of this class.
1087 cleanup(Info, OldStackSize);
1088 }
1089 private:
1090 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1091 unsigned NewEnd = OldStackSize;
1092 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1093 I != N; ++I) {
1094 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1095 // Full-expression cleanup of a lifetime-extended temporary: nothing
1096 // to do, just move this cleanup to the right place in the stack.
1097 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1098 ++NewEnd;
1099 } else {
1100 // End the lifetime of the object.
1101 Info.CleanupStack[I].endLifetime();
1102 }
1103 }
1104 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1105 Info.CleanupStack.end());
1106 }
1107 };
1108 typedef ScopeRAII<false> BlockScopeRAII;
1109 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001110}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001111
Richard Smitha8105bc2012-01-06 16:39:00 +00001112bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1113 CheckSubobjectKind CSK) {
1114 if (Invalid)
1115 return false;
1116 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001117 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001118 << CSK;
1119 setInvalid();
1120 return false;
1121 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001122 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1123 // must actually be at least one array element; even a VLA cannot have a
1124 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001125 return true;
1126}
1127
Richard Smith6f4f0f12017-10-20 22:56:25 +00001128void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1129 const Expr *E) {
1130 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1131 // Do not set the designator as invalid: we can represent this situation,
1132 // and correct handling of __builtin_object_size requires us to do so.
1133}
1134
Richard Smitha8105bc2012-01-06 16:39:00 +00001135void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001136 const Expr *E,
1137 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001138 // If we're complaining, we must be able to statically determine the size of
1139 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001140 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001141 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001142 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001143 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001144 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001145 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001146 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001147 setInvalid();
1148}
1149
Richard Smithf6f003a2011-12-16 19:06:07 +00001150CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1151 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001152 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001153 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1154 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001155 Info.CurrentCall = this;
1156 ++Info.CallStackDepth;
1157}
1158
1159CallStackFrame::~CallStackFrame() {
1160 assert(Info.CurrentCall == this && "calls retired out of order");
1161 --Info.CallStackDepth;
1162 Info.CurrentCall = Caller;
1163}
1164
Richard Smith08d6a2c2013-07-24 07:11:57 +00001165APValue &CallStackFrame::createTemporary(const void *Key,
1166 bool IsLifetimeExtended) {
1167 APValue &Result = Temporaries[Key];
1168 assert(Result.isUninit() && "temporary created multiple times");
1169 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1170 return Result;
1171}
1172
Richard Smith84401042013-06-03 05:03:02 +00001173static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001174
1175void EvalInfo::addCallStack(unsigned Limit) {
1176 // Determine which calls to skip, if any.
1177 unsigned ActiveCalls = CallStackDepth - 1;
1178 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1179 if (Limit && Limit < ActiveCalls) {
1180 SkipStart = Limit / 2 + Limit % 2;
1181 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001182 }
1183
Richard Smithf6f003a2011-12-16 19:06:07 +00001184 // Walk the call stack and add the diagnostics.
1185 unsigned CallIdx = 0;
1186 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1187 Frame = Frame->Caller, ++CallIdx) {
1188 // Skip this call?
1189 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1190 if (CallIdx == SkipStart) {
1191 // Note that we're skipping calls.
1192 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1193 << unsigned(ActiveCalls - Limit);
1194 }
1195 continue;
1196 }
1197
Richard Smith5179eb72016-06-28 19:03:57 +00001198 // Use a different note for an inheriting constructor, because from the
1199 // user's perspective it's not really a function at all.
1200 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1201 if (CD->isInheritingConstructor()) {
1202 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1203 << CD->getParent();
1204 continue;
1205 }
1206 }
1207
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001208 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001209 llvm::raw_svector_ostream Out(Buffer);
1210 describeCall(Frame, Out);
1211 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1212 }
1213}
1214
1215namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001216 struct ComplexValue {
1217 private:
1218 bool IsInt;
1219
1220 public:
1221 APSInt IntReal, IntImag;
1222 APFloat FloatReal, FloatImag;
1223
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001224 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001225
1226 void makeComplexFloat() { IsInt = false; }
1227 bool isComplexFloat() const { return !IsInt; }
1228 APFloat &getComplexFloatReal() { return FloatReal; }
1229 APFloat &getComplexFloatImag() { return FloatImag; }
1230
1231 void makeComplexInt() { IsInt = true; }
1232 bool isComplexInt() const { return IsInt; }
1233 APSInt &getComplexIntReal() { return IntReal; }
1234 APSInt &getComplexIntImag() { return IntImag; }
1235
Richard Smith2e312c82012-03-03 22:46:17 +00001236 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001237 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001238 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001239 else
Richard Smith2e312c82012-03-03 22:46:17 +00001240 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001241 }
Richard Smith2e312c82012-03-03 22:46:17 +00001242 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001243 assert(v.isComplexFloat() || v.isComplexInt());
1244 if (v.isComplexFloat()) {
1245 makeComplexFloat();
1246 FloatReal = v.getComplexFloatReal();
1247 FloatImag = v.getComplexFloatImag();
1248 } else {
1249 makeComplexInt();
1250 IntReal = v.getComplexIntReal();
1251 IntImag = v.getComplexIntImag();
1252 }
1253 }
John McCall93d91dc2010-05-07 17:22:02 +00001254 };
John McCall45d55e42010-05-07 21:00:08 +00001255
1256 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001257 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001258 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001259 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001260 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001261 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001262 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001263
Richard Smithce40ad62011-11-12 22:28:03 +00001264 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001265 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001266 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001267 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001268 SubobjectDesignator &getLValueDesignator() { return Designator; }
1269 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001270 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001271
Richard Smith2e312c82012-03-03 22:46:17 +00001272 void moveInto(APValue &V) const {
1273 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001274 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1275 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001276 else {
1277 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001278 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001279 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001280 }
John McCall45d55e42010-05-07 21:00:08 +00001281 }
Richard Smith2e312c82012-03-03 22:46:17 +00001282 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001283 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001284 Base = V.getLValueBase();
1285 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001286 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001287 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001288 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001289 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001290 }
1291
Tim Northover01503332017-05-26 02:16:00 +00001292 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001293#ifndef NDEBUG
1294 // We only allow a few types of invalid bases. Enforce that here.
1295 if (BInvalid) {
1296 const auto *E = B.get<const Expr *>();
1297 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1298 "Unexpected type of invalid base");
1299 }
1300#endif
1301
Richard Smithce40ad62011-11-12 22:28:03 +00001302 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001303 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001304 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001305 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001306 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001307 IsNullPtr = false;
1308 }
1309
1310 void setNull(QualType PointerTy, uint64_t TargetVal) {
1311 Base = (Expr *)nullptr;
1312 Offset = CharUnits::fromQuantity(TargetVal);
1313 InvalidBase = false;
1314 CallIndex = 0;
1315 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1316 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001317 }
1318
George Burgess IV3a03fab2015-09-04 21:28:13 +00001319 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1320 set(B, I, true);
1321 }
1322
Richard Smitha8105bc2012-01-06 16:39:00 +00001323 // Check that this LValue is not based on a null pointer. If it is, produce
1324 // a diagnostic and mark the designator as invalid.
1325 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1326 CheckSubobjectKind CSK) {
1327 if (Designator.Invalid)
1328 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001329 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001330 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001331 << CSK;
1332 Designator.setInvalid();
1333 return false;
1334 }
1335 return true;
1336 }
1337
1338 // Check this LValue refers to an object. If not, set the designator to be
1339 // invalid and emit a diagnostic.
1340 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001341 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001342 Designator.checkSubobject(Info, E, CSK);
1343 }
1344
1345 void addDecl(EvalInfo &Info, const Expr *E,
1346 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001347 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1348 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001349 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001350 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1351 if (!Designator.Entries.empty()) {
1352 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1353 Designator.setInvalid();
1354 return;
1355 }
Richard Smithefdb5032017-11-15 03:03:56 +00001356 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1357 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1358 Designator.FirstEntryIsAnUnsizedArray = true;
1359 Designator.addUnsizedArrayUnchecked(ElemTy);
1360 }
George Burgess IVe3763372016-12-22 02:50:20 +00001361 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001362 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001363 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1364 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001365 }
Richard Smith66c96992012-02-18 22:04:06 +00001366 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001367 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1368 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001369 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001370 void clearIsNullPointer() {
1371 IsNullPtr = false;
1372 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001373 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1374 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001375 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1376 // but we're not required to diagnose it and it's valid in C++.)
1377 if (!Index)
1378 return;
1379
1380 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1381 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1382 // offsets.
1383 uint64_t Offset64 = Offset.getQuantity();
1384 uint64_t ElemSize64 = ElementSize.getQuantity();
1385 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1386 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1387
1388 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001389 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001390 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001391 }
1392 void adjustOffset(CharUnits N) {
1393 Offset += N;
1394 if (N.getQuantity())
1395 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001396 }
John McCall45d55e42010-05-07 21:00:08 +00001397 };
Richard Smith027bf112011-11-17 22:56:20 +00001398
1399 struct MemberPtr {
1400 MemberPtr() {}
1401 explicit MemberPtr(const ValueDecl *Decl) :
1402 DeclAndIsDerivedMember(Decl, false), Path() {}
1403
1404 /// The member or (direct or indirect) field referred to by this member
1405 /// pointer, or 0 if this is a null member pointer.
1406 const ValueDecl *getDecl() const {
1407 return DeclAndIsDerivedMember.getPointer();
1408 }
1409 /// Is this actually a member of some type derived from the relevant class?
1410 bool isDerivedMember() const {
1411 return DeclAndIsDerivedMember.getInt();
1412 }
1413 /// Get the class which the declaration actually lives in.
1414 const CXXRecordDecl *getContainingRecord() const {
1415 return cast<CXXRecordDecl>(
1416 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1417 }
1418
Richard Smith2e312c82012-03-03 22:46:17 +00001419 void moveInto(APValue &V) const {
1420 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001421 }
Richard Smith2e312c82012-03-03 22:46:17 +00001422 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001423 assert(V.isMemberPointer());
1424 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1425 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1426 Path.clear();
1427 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1428 Path.insert(Path.end(), P.begin(), P.end());
1429 }
1430
1431 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1432 /// whether the member is a member of some class derived from the class type
1433 /// of the member pointer.
1434 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1435 /// Path - The path of base/derived classes from the member declaration's
1436 /// class (exclusive) to the class type of the member pointer (inclusive).
1437 SmallVector<const CXXRecordDecl*, 4> Path;
1438
1439 /// Perform a cast towards the class of the Decl (either up or down the
1440 /// hierarchy).
1441 bool castBack(const CXXRecordDecl *Class) {
1442 assert(!Path.empty());
1443 const CXXRecordDecl *Expected;
1444 if (Path.size() >= 2)
1445 Expected = Path[Path.size() - 2];
1446 else
1447 Expected = getContainingRecord();
1448 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1449 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1450 // if B does not contain the original member and is not a base or
1451 // derived class of the class containing the original member, the result
1452 // of the cast is undefined.
1453 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1454 // (D::*). We consider that to be a language defect.
1455 return false;
1456 }
1457 Path.pop_back();
1458 return true;
1459 }
1460 /// Perform a base-to-derived member pointer cast.
1461 bool castToDerived(const CXXRecordDecl *Derived) {
1462 if (!getDecl())
1463 return true;
1464 if (!isDerivedMember()) {
1465 Path.push_back(Derived);
1466 return true;
1467 }
1468 if (!castBack(Derived))
1469 return false;
1470 if (Path.empty())
1471 DeclAndIsDerivedMember.setInt(false);
1472 return true;
1473 }
1474 /// Perform a derived-to-base member pointer cast.
1475 bool castToBase(const CXXRecordDecl *Base) {
1476 if (!getDecl())
1477 return true;
1478 if (Path.empty())
1479 DeclAndIsDerivedMember.setInt(true);
1480 if (isDerivedMember()) {
1481 Path.push_back(Base);
1482 return true;
1483 }
1484 return castBack(Base);
1485 }
1486 };
Richard Smith357362d2011-12-13 06:39:58 +00001487
Richard Smith7bb00672012-02-01 01:42:44 +00001488 /// Compare two member pointers, which are assumed to be of the same type.
1489 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1490 if (!LHS.getDecl() || !RHS.getDecl())
1491 return !LHS.getDecl() && !RHS.getDecl();
1492 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1493 return false;
1494 return LHS.Path == RHS.Path;
1495 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001496}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001497
Richard Smith2e312c82012-03-03 22:46:17 +00001498static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001499static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1500 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001501 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001502static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1503 bool InvalidBaseOK = false);
1504static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1505 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001506static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1507 EvalInfo &Info);
1508static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001509static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001510static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001511 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001512static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001513static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001514static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1515 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001516static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001517
1518//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001519// Misc utilities
1520//===----------------------------------------------------------------------===//
1521
Richard Smithd6cc1982017-01-31 02:23:02 +00001522/// Negate an APSInt in place, converting it to a signed form if necessary, and
1523/// preserving its value (by extending by up to one bit as needed).
1524static void negateAsSigned(APSInt &Int) {
1525 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1526 Int = Int.extend(Int.getBitWidth() + 1);
1527 Int.setIsSigned(true);
1528 }
1529 Int = -Int;
1530}
1531
Richard Smith84401042013-06-03 05:03:02 +00001532/// Produce a string describing the given constexpr call.
1533static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1534 unsigned ArgIndex = 0;
1535 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1536 !isa<CXXConstructorDecl>(Frame->Callee) &&
1537 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1538
1539 if (!IsMemberCall)
1540 Out << *Frame->Callee << '(';
1541
1542 if (Frame->This && IsMemberCall) {
1543 APValue Val;
1544 Frame->This->moveInto(Val);
1545 Val.printPretty(Out, Frame->Info.Ctx,
1546 Frame->This->Designator.MostDerivedType);
1547 // FIXME: Add parens around Val if needed.
1548 Out << "->" << *Frame->Callee << '(';
1549 IsMemberCall = false;
1550 }
1551
1552 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1553 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1554 if (ArgIndex > (unsigned)IsMemberCall)
1555 Out << ", ";
1556
1557 const ParmVarDecl *Param = *I;
1558 const APValue &Arg = Frame->Arguments[ArgIndex];
1559 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1560
1561 if (ArgIndex == 0 && IsMemberCall)
1562 Out << "->" << *Frame->Callee << '(';
1563 }
1564
1565 Out << ')';
1566}
1567
Richard Smithd9f663b2013-04-22 15:31:51 +00001568/// Evaluate an expression to see if it had side-effects, and discard its
1569/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001570/// \return \c true if the caller should keep evaluating.
1571static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001572 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001573 if (!Evaluate(Scratch, Info, E))
1574 // We don't need the value, but we might have skipped a side effect here.
1575 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001576 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001577}
1578
Richard Smithd62306a2011-11-10 06:34:14 +00001579/// Should this call expression be treated as a string literal?
1580static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001581 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001582 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1583 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1584}
1585
Richard Smithce40ad62011-11-12 22:28:03 +00001586static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001587 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1588 // constant expression of pointer type that evaluates to...
1589
1590 // ... a null pointer value, or a prvalue core constant expression of type
1591 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001592 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001593
Richard Smithce40ad62011-11-12 22:28:03 +00001594 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1595 // ... the address of an object with static storage duration,
1596 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1597 return VD->hasGlobalStorage();
1598 // ... the address of a function,
1599 return isa<FunctionDecl>(D);
1600 }
1601
1602 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001603 switch (E->getStmtClass()) {
1604 default:
1605 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001606 case Expr::CompoundLiteralExprClass: {
1607 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1608 return CLE->isFileScope() && CLE->isLValue();
1609 }
Richard Smithe6c01442013-06-05 00:46:14 +00001610 case Expr::MaterializeTemporaryExprClass:
1611 // A materialized temporary might have been lifetime-extended to static
1612 // storage duration.
1613 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001614 // A string literal has static storage duration.
1615 case Expr::StringLiteralClass:
1616 case Expr::PredefinedExprClass:
1617 case Expr::ObjCStringLiteralClass:
1618 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001619 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001620 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001621 return true;
1622 case Expr::CallExprClass:
1623 return IsStringLiteralCall(cast<CallExpr>(E));
1624 // For GCC compatibility, &&label has static storage duration.
1625 case Expr::AddrLabelExprClass:
1626 return true;
1627 // A Block literal expression may be used as the initialization value for
1628 // Block variables at global or local static scope.
1629 case Expr::BlockExprClass:
1630 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001631 case Expr::ImplicitValueInitExprClass:
1632 // FIXME:
1633 // We can never form an lvalue with an implicit value initialization as its
1634 // base through expression evaluation, so these only appear in one case: the
1635 // implicit variable declaration we invent when checking whether a constexpr
1636 // constructor can produce a constant expression. We must assume that such
1637 // an expression might be a global lvalue.
1638 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001639 }
John McCall95007602010-05-10 23:27:23 +00001640}
1641
Richard Smithb228a862012-02-15 02:18:13 +00001642static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1643 assert(Base && "no location for a null lvalue");
1644 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1645 if (VD)
1646 Info.Note(VD->getLocation(), diag::note_declared_at);
1647 else
Ted Kremenek28831752012-08-23 20:46:57 +00001648 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001649 diag::note_constexpr_temporary_here);
1650}
1651
Richard Smith80815602011-11-07 05:07:52 +00001652/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001653/// value for an address or reference constant expression. Return true if we
1654/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001655static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1656 QualType Type, const LValue &LVal) {
1657 bool IsReferenceType = Type->isReferenceType();
1658
Richard Smith357362d2011-12-13 06:39:58 +00001659 APValue::LValueBase Base = LVal.getLValueBase();
1660 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1661
Richard Smith0dea49e2012-02-18 04:58:18 +00001662 // Check that the object is a global. Note that the fake 'this' object we
1663 // manufacture when checking potential constant expressions is conservatively
1664 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001665 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001666 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001667 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001668 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001669 << IsReferenceType << !Designator.Entries.empty()
1670 << !!VD << VD;
1671 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001672 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001673 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001674 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001675 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001676 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001677 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001678 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001679 LVal.getLValueCallIndex() == 0) &&
1680 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001681
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001682 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1683 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001684 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001685 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001686 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001687
Hans Wennborg82dd8772014-06-25 22:19:48 +00001688 // A dllimport variable never acts like a constant.
1689 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001690 return false;
1691 }
1692 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1693 // __declspec(dllimport) must be handled very carefully:
1694 // We must never initialize an expression with the thunk in C++.
1695 // Doing otherwise would allow the same id-expression to yield
1696 // different addresses for the same function in different translation
1697 // units. However, this means that we must dynamically initialize the
1698 // expression with the contents of the import address table at runtime.
1699 //
1700 // The C language has no notion of ODR; furthermore, it has no notion of
1701 // dynamic initialization. This means that we are permitted to
1702 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001703 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001704 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001705 }
1706 }
1707
Richard Smitha8105bc2012-01-06 16:39:00 +00001708 // Allow address constant expressions to be past-the-end pointers. This is
1709 // an extension: the standard requires them to point to an object.
1710 if (!IsReferenceType)
1711 return true;
1712
1713 // A reference constant expression must refer to an object.
1714 if (!Base) {
1715 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001716 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001717 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001718 }
1719
Richard Smith357362d2011-12-13 06:39:58 +00001720 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001721 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001722 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001723 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001724 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001725 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001726 }
1727
Richard Smith80815602011-11-07 05:07:52 +00001728 return true;
1729}
1730
Reid Klecknercd016d82017-07-07 22:04:29 +00001731/// Member pointers are constant expressions unless they point to a
1732/// non-virtual dllimport member function.
1733static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1734 SourceLocation Loc,
1735 QualType Type,
1736 const APValue &Value) {
1737 const ValueDecl *Member = Value.getMemberPointerDecl();
1738 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1739 if (!FD)
1740 return true;
1741 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1742}
1743
Richard Smithfddd3842011-12-30 21:15:51 +00001744/// Check that this core constant expression is of literal type, and if not,
1745/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001746static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001747 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001748 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001749 return true;
1750
Richard Smith7525ff62013-05-09 07:14:00 +00001751 // C++1y: A constant initializer for an object o [...] may also invoke
1752 // constexpr constructors for o and its subobjects even if those objects
1753 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001754 //
1755 // C++11 missed this detail for aggregates, so classes like this:
1756 // struct foo_t { union { int i; volatile int j; } u; };
1757 // are not (obviously) initializable like so:
1758 // __attribute__((__require_constant_initialization__))
1759 // static const foo_t x = {{0}};
1760 // because "i" is a subobject with non-literal initialization (due to the
1761 // volatile member of the union). See:
1762 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1763 // Therefore, we use the C++1y behavior.
1764 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001765 return true;
1766
Richard Smithfddd3842011-12-30 21:15:51 +00001767 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001768 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001769 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001770 << E->getType();
1771 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001772 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001773 return false;
1774}
1775
Richard Smith0b0a0b62011-10-29 20:57:55 +00001776/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001777/// constant expression. If not, report an appropriate diagnostic. Does not
1778/// check that the expression is of literal type.
1779static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1780 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001781 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001782 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001783 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001784 return false;
1785 }
1786
Richard Smith77be48a2014-07-31 06:31:19 +00001787 // We allow _Atomic(T) to be initialized from anything that T can be
1788 // initialized from.
1789 if (const AtomicType *AT = Type->getAs<AtomicType>())
1790 Type = AT->getValueType();
1791
Richard Smithb228a862012-02-15 02:18:13 +00001792 // Core issue 1454: For a literal constant expression of array or class type,
1793 // each subobject of its value shall have been initialized by a constant
1794 // expression.
1795 if (Value.isArray()) {
1796 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1797 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1798 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1799 Value.getArrayInitializedElt(I)))
1800 return false;
1801 }
1802 if (!Value.hasArrayFiller())
1803 return true;
1804 return CheckConstantExpression(Info, DiagLoc, EltTy,
1805 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001806 }
Richard Smithb228a862012-02-15 02:18:13 +00001807 if (Value.isUnion() && Value.getUnionField()) {
1808 return CheckConstantExpression(Info, DiagLoc,
1809 Value.getUnionField()->getType(),
1810 Value.getUnionValue());
1811 }
1812 if (Value.isStruct()) {
1813 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1814 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1815 unsigned BaseIndex = 0;
1816 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1817 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1818 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1819 Value.getStructBase(BaseIndex)))
1820 return false;
1821 }
1822 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001823 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00001824 if (I->isUnnamedBitfield())
1825 continue;
1826
David Blaikie2d7c57e2012-04-30 02:36:29 +00001827 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1828 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001829 return false;
1830 }
1831 }
1832
1833 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001834 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001835 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001836 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1837 }
1838
Reid Klecknercd016d82017-07-07 22:04:29 +00001839 if (Value.isMemberPointer())
1840 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1841
Richard Smithb228a862012-02-15 02:18:13 +00001842 // Everything else is fine.
1843 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001844}
1845
Benjamin Kramer8407df72015-03-09 16:47:52 +00001846static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001847 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001848}
1849
1850static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001851 if (Value.CallIndex)
1852 return false;
1853 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1854 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001855}
1856
Richard Smithcecf1842011-11-01 21:06:14 +00001857static bool IsWeakLValue(const LValue &Value) {
1858 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001859 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001860}
1861
David Majnemerb5116032014-12-09 23:32:34 +00001862static bool isZeroSized(const LValue &Value) {
1863 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001864 if (Decl && isa<VarDecl>(Decl)) {
1865 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001866 if (Ty->isArrayType())
1867 return Ty->isIncompleteType() ||
1868 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001869 }
1870 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001871}
1872
Richard Smith2e312c82012-03-03 22:46:17 +00001873static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001874 // A null base expression indicates a null pointer. These are always
1875 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001876 if (!Value.getLValueBase()) {
1877 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001878 return true;
1879 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001880
Richard Smith027bf112011-11-17 22:56:20 +00001881 // We have a non-null base. These are generally known to be true, but if it's
1882 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001883 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001884 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001885 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001886}
1887
Richard Smith2e312c82012-03-03 22:46:17 +00001888static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001889 switch (Val.getKind()) {
1890 case APValue::Uninitialized:
1891 return false;
1892 case APValue::Int:
1893 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001894 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001895 case APValue::Float:
1896 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001897 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001898 case APValue::ComplexInt:
1899 Result = Val.getComplexIntReal().getBoolValue() ||
1900 Val.getComplexIntImag().getBoolValue();
1901 return true;
1902 case APValue::ComplexFloat:
1903 Result = !Val.getComplexFloatReal().isZero() ||
1904 !Val.getComplexFloatImag().isZero();
1905 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001906 case APValue::LValue:
1907 return EvalPointerValueAsBool(Val, Result);
1908 case APValue::MemberPointer:
1909 Result = Val.getMemberPointerDecl();
1910 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001911 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001912 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001913 case APValue::Struct:
1914 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001915 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001916 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001917 }
1918
Richard Smith11562c52011-10-28 17:51:58 +00001919 llvm_unreachable("unknown APValue kind");
1920}
1921
1922static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1923 EvalInfo &Info) {
1924 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001925 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001926 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001927 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001928 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001929}
1930
Richard Smith357362d2011-12-13 06:39:58 +00001931template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001932static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001933 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001934 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001935 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001936 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001937}
1938
1939static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1940 QualType SrcType, const APFloat &Value,
1941 QualType DestType, APSInt &Result) {
1942 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001943 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001944 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001945
Richard Smith357362d2011-12-13 06:39:58 +00001946 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001947 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001948 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1949 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001950 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001951 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001952}
1953
Richard Smith357362d2011-12-13 06:39:58 +00001954static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1955 QualType SrcType, QualType DestType,
1956 APFloat &Result) {
1957 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001958 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001959 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1960 APFloat::rmNearestTiesToEven, &ignored)
1961 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001962 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001963 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001964}
1965
Richard Smith911e1422012-01-30 22:27:01 +00001966static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1967 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001968 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001969 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001970 APSInt Result = Value;
1971 // Figure out if this is a truncate, extend or noop cast.
1972 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001973 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001974 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001975 return Result;
1976}
1977
Richard Smith357362d2011-12-13 06:39:58 +00001978static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1979 QualType SrcType, const APSInt &Value,
1980 QualType DestType, APFloat &Result) {
1981 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1982 if (Result.convertFromAPInt(Value, Value.isSigned(),
1983 APFloat::rmNearestTiesToEven)
1984 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001985 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001986 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001987}
1988
Richard Smith49ca8aa2013-08-06 07:09:20 +00001989static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1990 APValue &Value, const FieldDecl *FD) {
1991 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1992
1993 if (!Value.isInt()) {
1994 // Trying to store a pointer-cast-to-integer into a bitfield.
1995 // FIXME: In this case, we should provide the diagnostic for casting
1996 // a pointer to an integer.
1997 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001998 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001999 return false;
2000 }
2001
2002 APSInt &Int = Value.getInt();
2003 unsigned OldBitWidth = Int.getBitWidth();
2004 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2005 if (NewBitWidth < OldBitWidth)
2006 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2007 return true;
2008}
2009
Eli Friedman803acb32011-12-22 03:51:45 +00002010static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2011 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002012 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002013 if (!Evaluate(SVal, Info, E))
2014 return false;
2015 if (SVal.isInt()) {
2016 Res = SVal.getInt();
2017 return true;
2018 }
2019 if (SVal.isFloat()) {
2020 Res = SVal.getFloat().bitcastToAPInt();
2021 return true;
2022 }
2023 if (SVal.isVector()) {
2024 QualType VecTy = E->getType();
2025 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2026 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2027 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2028 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2029 Res = llvm::APInt::getNullValue(VecSize);
2030 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2031 APValue &Elt = SVal.getVectorElt(i);
2032 llvm::APInt EltAsInt;
2033 if (Elt.isInt()) {
2034 EltAsInt = Elt.getInt();
2035 } else if (Elt.isFloat()) {
2036 EltAsInt = Elt.getFloat().bitcastToAPInt();
2037 } else {
2038 // Don't try to handle vectors of anything other than int or float
2039 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002040 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002041 return false;
2042 }
2043 unsigned BaseEltSize = EltAsInt.getBitWidth();
2044 if (BigEndian)
2045 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2046 else
2047 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2048 }
2049 return true;
2050 }
2051 // Give up if the input isn't an int, float, or vector. For example, we
2052 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002053 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002054 return false;
2055}
2056
Richard Smith43e77732013-05-07 04:50:00 +00002057/// Perform the given integer operation, which is known to need at most BitWidth
2058/// bits, and check for overflow in the original type (if that type was not an
2059/// unsigned type).
2060template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002061static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2062 const APSInt &LHS, const APSInt &RHS,
2063 unsigned BitWidth, Operation Op,
2064 APSInt &Result) {
2065 if (LHS.isUnsigned()) {
2066 Result = Op(LHS, RHS);
2067 return true;
2068 }
Richard Smith43e77732013-05-07 04:50:00 +00002069
2070 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002071 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002072 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002073 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002074 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002075 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002076 << Result.toString(10) << E->getType();
2077 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002078 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002079 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002080 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002081}
2082
2083/// Perform the given binary integer operation.
2084static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2085 BinaryOperatorKind Opcode, APSInt RHS,
2086 APSInt &Result) {
2087 switch (Opcode) {
2088 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002089 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002090 return false;
2091 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002092 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2093 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002094 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002095 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2096 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002097 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002098 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2099 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002100 case BO_And: Result = LHS & RHS; return true;
2101 case BO_Xor: Result = LHS ^ RHS; return true;
2102 case BO_Or: Result = LHS | RHS; return true;
2103 case BO_Div:
2104 case BO_Rem:
2105 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002106 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002107 return false;
2108 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002109 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2110 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2111 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002112 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2113 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002114 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2115 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002116 return true;
2117 case BO_Shl: {
2118 if (Info.getLangOpts().OpenCL)
2119 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2120 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2121 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2122 RHS.isUnsigned());
2123 else if (RHS.isSigned() && RHS.isNegative()) {
2124 // During constant-folding, a negative shift is an opposite shift. Such
2125 // a shift is not a constant expression.
2126 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2127 RHS = -RHS;
2128 goto shift_right;
2129 }
2130 shift_left:
2131 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2132 // the shifted type.
2133 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2134 if (SA != RHS) {
2135 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2136 << RHS << E->getType() << LHS.getBitWidth();
2137 } else if (LHS.isSigned()) {
2138 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2139 // operand, and must not overflow the corresponding unsigned type.
2140 if (LHS.isNegative())
2141 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2142 else if (LHS.countLeadingZeros() < SA)
2143 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2144 }
2145 Result = LHS << SA;
2146 return true;
2147 }
2148 case BO_Shr: {
2149 if (Info.getLangOpts().OpenCL)
2150 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2151 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2152 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2153 RHS.isUnsigned());
2154 else if (RHS.isSigned() && RHS.isNegative()) {
2155 // During constant-folding, a negative shift is an opposite shift. Such a
2156 // shift is not a constant expression.
2157 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2158 RHS = -RHS;
2159 goto shift_left;
2160 }
2161 shift_right:
2162 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2163 // shifted type.
2164 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2165 if (SA != RHS)
2166 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2167 << RHS << E->getType() << LHS.getBitWidth();
2168 Result = LHS >> SA;
2169 return true;
2170 }
2171
2172 case BO_LT: Result = LHS < RHS; return true;
2173 case BO_GT: Result = LHS > RHS; return true;
2174 case BO_LE: Result = LHS <= RHS; return true;
2175 case BO_GE: Result = LHS >= RHS; return true;
2176 case BO_EQ: Result = LHS == RHS; return true;
2177 case BO_NE: Result = LHS != RHS; return true;
2178 }
2179}
2180
Richard Smith861b5b52013-05-07 23:34:45 +00002181/// Perform the given binary floating-point operation, in-place, on LHS.
2182static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2183 APFloat &LHS, BinaryOperatorKind Opcode,
2184 const APFloat &RHS) {
2185 switch (Opcode) {
2186 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002187 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002188 return false;
2189 case BO_Mul:
2190 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2191 break;
2192 case BO_Add:
2193 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2194 break;
2195 case BO_Sub:
2196 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2197 break;
2198 case BO_Div:
2199 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2200 break;
2201 }
2202
Richard Smith0c6124b2015-12-03 01:36:22 +00002203 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002204 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002205 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002206 }
Richard Smith861b5b52013-05-07 23:34:45 +00002207 return true;
2208}
2209
Richard Smitha8105bc2012-01-06 16:39:00 +00002210/// Cast an lvalue referring to a base subobject to a derived class, by
2211/// truncating the lvalue's path to the given length.
2212static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2213 const RecordDecl *TruncatedType,
2214 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002215 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002216
2217 // Check we actually point to a derived class object.
2218 if (TruncatedElements == D.Entries.size())
2219 return true;
2220 assert(TruncatedElements >= D.MostDerivedPathLength &&
2221 "not casting to a derived class");
2222 if (!Result.checkSubobject(Info, E, CSK_Derived))
2223 return false;
2224
2225 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002226 const RecordDecl *RD = TruncatedType;
2227 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002228 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002229 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2230 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002231 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002232 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002233 else
Richard Smithd62306a2011-11-10 06:34:14 +00002234 Result.Offset -= Layout.getBaseClassOffset(Base);
2235 RD = Base;
2236 }
Richard Smith027bf112011-11-17 22:56:20 +00002237 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002238 return true;
2239}
2240
John McCalld7bca762012-05-01 00:38:49 +00002241static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002242 const CXXRecordDecl *Derived,
2243 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002244 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002245 if (!RL) {
2246 if (Derived->isInvalidDecl()) return false;
2247 RL = &Info.Ctx.getASTRecordLayout(Derived);
2248 }
2249
Richard Smithd62306a2011-11-10 06:34:14 +00002250 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002251 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002252 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002253}
2254
Richard Smitha8105bc2012-01-06 16:39:00 +00002255static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002256 const CXXRecordDecl *DerivedDecl,
2257 const CXXBaseSpecifier *Base) {
2258 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2259
John McCalld7bca762012-05-01 00:38:49 +00002260 if (!Base->isVirtual())
2261 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002262
Richard Smitha8105bc2012-01-06 16:39:00 +00002263 SubobjectDesignator &D = Obj.Designator;
2264 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002265 return false;
2266
Richard Smitha8105bc2012-01-06 16:39:00 +00002267 // Extract most-derived object and corresponding type.
2268 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2269 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2270 return false;
2271
2272 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002273 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002274 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2275 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002276 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002277 return true;
2278}
2279
Richard Smith84401042013-06-03 05:03:02 +00002280static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2281 QualType Type, LValue &Result) {
2282 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2283 PathE = E->path_end();
2284 PathI != PathE; ++PathI) {
2285 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2286 *PathI))
2287 return false;
2288 Type = (*PathI)->getType();
2289 }
2290 return true;
2291}
2292
Richard Smithd62306a2011-11-10 06:34:14 +00002293/// Update LVal to refer to the given field, which must be a member of the type
2294/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002295static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002296 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002297 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002298 if (!RL) {
2299 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002300 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002301 }
Richard Smithd62306a2011-11-10 06:34:14 +00002302
2303 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002304 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002305 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002306 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002307}
2308
Richard Smith1b78b3d2012-01-25 22:15:11 +00002309/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002310static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002311 LValue &LVal,
2312 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002313 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002314 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002315 return false;
2316 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002317}
2318
Richard Smithd62306a2011-11-10 06:34:14 +00002319/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002320static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2321 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002322 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2323 // extension.
2324 if (Type->isVoidType() || Type->isFunctionType()) {
2325 Size = CharUnits::One();
2326 return true;
2327 }
2328
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002329 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002330 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002331 return false;
2332 }
2333
Richard Smithd62306a2011-11-10 06:34:14 +00002334 if (!Type->isConstantSizeType()) {
2335 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002336 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002337 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002338 return false;
2339 }
2340
2341 Size = Info.Ctx.getTypeSizeInChars(Type);
2342 return true;
2343}
2344
2345/// Update a pointer value to model pointer arithmetic.
2346/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002347/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002348/// \param LVal - The pointer value to be updated.
2349/// \param EltTy - The pointee type represented by LVal.
2350/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002351static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2352 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002353 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002354 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002355 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002356 return false;
2357
Yaxun Liu402804b2016-12-15 08:09:08 +00002358 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002359 return true;
2360}
2361
Richard Smithd6cc1982017-01-31 02:23:02 +00002362static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2363 LValue &LVal, QualType EltTy,
2364 int64_t Adjustment) {
2365 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2366 APSInt::get(Adjustment));
2367}
2368
Richard Smith66c96992012-02-18 22:04:06 +00002369/// Update an lvalue to refer to a component of a complex number.
2370/// \param Info - Information about the ongoing evaluation.
2371/// \param LVal - The lvalue to be updated.
2372/// \param EltTy - The complex number's component type.
2373/// \param Imag - False for the real component, true for the imaginary.
2374static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2375 LValue &LVal, QualType EltTy,
2376 bool Imag) {
2377 if (Imag) {
2378 CharUnits SizeOfComponent;
2379 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2380 return false;
2381 LVal.Offset += SizeOfComponent;
2382 }
2383 LVal.addComplex(Info, E, EltTy, Imag);
2384 return true;
2385}
2386
Faisal Vali051e3a22017-02-16 04:12:21 +00002387static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2388 QualType Type, const LValue &LVal,
2389 APValue &RVal);
2390
Richard Smith27908702011-10-24 17:54:18 +00002391/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002392///
2393/// \param Info Information about the ongoing evaluation.
2394/// \param E An expression to be used when printing diagnostics.
2395/// \param VD The variable whose initializer should be obtained.
2396/// \param Frame The frame in which the variable was created. Must be null
2397/// if this variable is not local to the evaluation.
2398/// \param Result Filled in with a pointer to the value of the variable.
2399static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2400 const VarDecl *VD, CallStackFrame *Frame,
2401 APValue *&Result) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002402
Richard Smith254a73d2011-10-28 22:34:42 +00002403 // If this is a parameter to an active constexpr function call, perform
2404 // argument substitution.
2405 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002406 // Assume arguments of a potential constant expression are unknown
2407 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002408 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002409 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002410 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002411 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002412 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002413 }
Richard Smith3229b742013-05-05 21:17:10 +00002414 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002415 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002416 }
Richard Smith27908702011-10-24 17:54:18 +00002417
Richard Smithd9f663b2013-04-22 15:31:51 +00002418 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002419 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002420 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002421 if (!Result) {
2422 // Assume variables referenced within a lambda's call operator that were
2423 // not declared within the call operator are captures and during checking
2424 // of a potential constant expression, assume they are unknown constant
2425 // expressions.
2426 assert(isLambdaCallOperator(Frame->Callee) &&
2427 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2428 "missing value for local variable");
2429 if (Info.checkingPotentialConstantExpression())
2430 return false;
2431 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002432 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002433 diag::note_unimplemented_constexpr_lambda_feature_ast)
2434 << "captures not currently allowed";
2435 return false;
2436 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002437 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002438 }
2439
Richard Smithd0b4dd62011-12-19 06:19:21 +00002440 // Dig out the initializer, and use the declaration which it's attached to.
2441 const Expr *Init = VD->getAnyInitializer(VD);
2442 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002443 // If we're checking a potential constant expression, the variable could be
2444 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002445 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002446 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002447 return false;
2448 }
2449
Richard Smithd62306a2011-11-10 06:34:14 +00002450 // If we're currently evaluating the initializer of this declaration, use that
2451 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002452 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002453 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002454 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002455 }
2456
Richard Smithcecf1842011-11-01 21:06:14 +00002457 // Never evaluate the initializer of a weak variable. We can't be sure that
2458 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002459 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002460 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002461 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002462 }
Richard Smithcecf1842011-11-01 21:06:14 +00002463
Richard Smithd0b4dd62011-12-19 06:19:21 +00002464 // Check that we can fold the initializer. In C++, we will have already done
2465 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002466 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002467 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002468 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002469 Notes.size() + 1) << VD;
2470 Info.Note(VD->getLocation(), diag::note_declared_at);
2471 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002472 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002473 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002474 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002475 Notes.size() + 1) << VD;
2476 Info.Note(VD->getLocation(), diag::note_declared_at);
2477 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002478 }
Richard Smith27908702011-10-24 17:54:18 +00002479
Richard Smith3229b742013-05-05 21:17:10 +00002480 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002481 return true;
Richard Smith27908702011-10-24 17:54:18 +00002482}
2483
Richard Smith11562c52011-10-28 17:51:58 +00002484static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002485 Qualifiers Quals = T.getQualifiers();
2486 return Quals.hasConst() && !Quals.hasVolatile();
2487}
2488
Richard Smithe97cbd72011-11-11 04:05:33 +00002489/// Get the base index of the given base class within an APValue representing
2490/// the given derived class.
2491static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2492 const CXXRecordDecl *Base) {
2493 Base = Base->getCanonicalDecl();
2494 unsigned Index = 0;
2495 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2496 E = Derived->bases_end(); I != E; ++I, ++Index) {
2497 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2498 return Index;
2499 }
2500
2501 llvm_unreachable("base class missing from derived class's bases list");
2502}
2503
Richard Smith3da88fa2013-04-26 14:36:30 +00002504/// Extract the value of a character from a string literal.
2505static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2506 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002507 // FIXME: Support MakeStringConstant
2508 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2509 std::string Str;
2510 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2511 assert(Index <= Str.size() && "Index too large");
2512 return APSInt::getUnsigned(Str.c_str()[Index]);
2513 }
2514
Alexey Bataevec474782014-10-09 08:45:04 +00002515 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2516 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002517 const StringLiteral *S = cast<StringLiteral>(Lit);
2518 const ConstantArrayType *CAT =
2519 Info.Ctx.getAsConstantArrayType(S->getType());
2520 assert(CAT && "string literal isn't an array");
2521 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002522 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002523
2524 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002525 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002526 if (Index < S->getLength())
2527 Value = S->getCodeUnit(Index);
2528 return Value;
2529}
2530
Richard Smith3da88fa2013-04-26 14:36:30 +00002531// Expand a string literal into an array of characters.
2532static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2533 APValue &Result) {
2534 const StringLiteral *S = cast<StringLiteral>(Lit);
2535 const ConstantArrayType *CAT =
2536 Info.Ctx.getAsConstantArrayType(S->getType());
2537 assert(CAT && "string literal isn't an array");
2538 QualType CharType = CAT->getElementType();
2539 assert(CharType->isIntegerType() && "unexpected character type");
2540
2541 unsigned Elts = CAT->getSize().getZExtValue();
2542 Result = APValue(APValue::UninitArray(),
2543 std::min(S->getLength(), Elts), Elts);
2544 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2545 CharType->isUnsignedIntegerType());
2546 if (Result.hasArrayFiller())
2547 Result.getArrayFiller() = APValue(Value);
2548 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2549 Value = S->getCodeUnit(I);
2550 Result.getArrayInitializedElt(I) = APValue(Value);
2551 }
2552}
2553
2554// Expand an array so that it has more than Index filled elements.
2555static void expandArray(APValue &Array, unsigned Index) {
2556 unsigned Size = Array.getArraySize();
2557 assert(Index < Size);
2558
2559 // Always at least double the number of elements for which we store a value.
2560 unsigned OldElts = Array.getArrayInitializedElts();
2561 unsigned NewElts = std::max(Index+1, OldElts * 2);
2562 NewElts = std::min(Size, std::max(NewElts, 8u));
2563
2564 // Copy the data across.
2565 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2566 for (unsigned I = 0; I != OldElts; ++I)
2567 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2568 for (unsigned I = OldElts; I != NewElts; ++I)
2569 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2570 if (NewValue.hasArrayFiller())
2571 NewValue.getArrayFiller() = Array.getArrayFiller();
2572 Array.swap(NewValue);
2573}
2574
Richard Smithb01fe402014-09-16 01:24:02 +00002575/// Determine whether a type would actually be read by an lvalue-to-rvalue
2576/// conversion. If it's of class type, we may assume that the copy operation
2577/// is trivial. Note that this is never true for a union type with fields
2578/// (because the copy always "reads" the active member) and always true for
2579/// a non-class type.
2580static bool isReadByLvalueToRvalueConversion(QualType T) {
2581 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2582 if (!RD || (RD->isUnion() && !RD->field_empty()))
2583 return true;
2584 if (RD->isEmpty())
2585 return false;
2586
2587 for (auto *Field : RD->fields())
2588 if (isReadByLvalueToRvalueConversion(Field->getType()))
2589 return true;
2590
2591 for (auto &BaseSpec : RD->bases())
2592 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2593 return true;
2594
2595 return false;
2596}
2597
2598/// Diagnose an attempt to read from any unreadable field within the specified
2599/// type, which might be a class type.
2600static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2601 QualType T) {
2602 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2603 if (!RD)
2604 return false;
2605
2606 if (!RD->hasMutableFields())
2607 return false;
2608
2609 for (auto *Field : RD->fields()) {
2610 // If we're actually going to read this field in some way, then it can't
2611 // be mutable. If we're in a union, then assigning to a mutable field
2612 // (even an empty one) can change the active member, so that's not OK.
2613 // FIXME: Add core issue number for the union case.
2614 if (Field->isMutable() &&
2615 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002616 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002617 Info.Note(Field->getLocation(), diag::note_declared_at);
2618 return true;
2619 }
2620
2621 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2622 return true;
2623 }
2624
2625 for (auto &BaseSpec : RD->bases())
2626 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2627 return true;
2628
2629 // All mutable fields were empty, and thus not actually read.
2630 return false;
2631}
2632
Richard Smith861b5b52013-05-07 23:34:45 +00002633/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002634enum AccessKinds {
2635 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002636 AK_Assign,
2637 AK_Increment,
2638 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002639};
2640
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002641namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002642/// A handle to a complete object (an object that is not a subobject of
2643/// another object).
2644struct CompleteObject {
2645 /// The value of the complete object.
2646 APValue *Value;
2647 /// The type of the complete object.
2648 QualType Type;
2649
Craig Topper36250ad2014-05-12 05:36:57 +00002650 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002651 CompleteObject(APValue *Value, QualType Type)
2652 : Value(Value), Type(Type) {
2653 assert(Value && "missing value for complete object");
2654 }
2655
Aaron Ballman67347662015-02-15 22:00:28 +00002656 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002657};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002658} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002659
Richard Smith3da88fa2013-04-26 14:36:30 +00002660/// Find the designated sub-object of an rvalue.
2661template<typename SubobjectHandler>
2662typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002663findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002664 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002665 if (Sub.Invalid)
2666 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002667 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002668 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002669 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002670 Info.FFDiag(E, Sub.isOnePastTheEnd()
2671 ? diag::note_constexpr_access_past_end
2672 : diag::note_constexpr_access_unsized_array)
2673 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002674 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002675 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002676 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002677 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002678
Richard Smith3229b742013-05-05 21:17:10 +00002679 APValue *O = Obj.Value;
2680 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002681 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002682
Richard Smithd62306a2011-11-10 06:34:14 +00002683 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002684 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2685 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002686 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002687 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002688 return handler.failed();
2689 }
2690
Richard Smith49ca8aa2013-08-06 07:09:20 +00002691 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002692 // If we are reading an object of class type, there may still be more
2693 // things we need to check: if there are any mutable subobjects, we
2694 // cannot perform this read. (This only happens when performing a trivial
2695 // copy or assignment.)
2696 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2697 diagnoseUnreadableFields(Info, E, ObjType))
2698 return handler.failed();
2699
Richard Smith49ca8aa2013-08-06 07:09:20 +00002700 if (!handler.found(*O, ObjType))
2701 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002702
Richard Smith49ca8aa2013-08-06 07:09:20 +00002703 // If we modified a bit-field, truncate it to the right width.
2704 if (handler.AccessKind != AK_Read &&
2705 LastField && LastField->isBitField() &&
2706 !truncateBitfieldValue(Info, E, *O, LastField))
2707 return false;
2708
2709 return true;
2710 }
2711
Craig Topper36250ad2014-05-12 05:36:57 +00002712 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002713 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002714 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002715 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002716 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002717 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002718 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002719 // Note, it should not be possible to form a pointer with a valid
2720 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002721 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002722 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002723 << handler.AccessKind;
2724 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002725 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002726 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002727 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002728
2729 ObjType = CAT->getElementType();
2730
Richard Smith14a94132012-02-17 03:35:37 +00002731 // An array object is represented as either an Array APValue or as an
2732 // LValue which refers to a string literal.
2733 if (O->isLValue()) {
2734 assert(I == N - 1 && "extracting subobject of character?");
2735 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002736 if (handler.AccessKind != AK_Read)
2737 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2738 *O);
2739 else
2740 return handler.foundString(*O, ObjType, Index);
2741 }
2742
2743 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002744 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002745 else if (handler.AccessKind != AK_Read) {
2746 expandArray(*O, Index);
2747 O = &O->getArrayInitializedElt(Index);
2748 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002749 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002750 } else if (ObjType->isAnyComplexType()) {
2751 // Next subobject is a complex number.
2752 uint64_t Index = Sub.Entries[I].ArrayIndex;
2753 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002754 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002755 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002756 << handler.AccessKind;
2757 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002758 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002759 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002760 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002761
2762 bool WasConstQualified = ObjType.isConstQualified();
2763 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2764 if (WasConstQualified)
2765 ObjType.addConst();
2766
Richard Smith66c96992012-02-18 22:04:06 +00002767 assert(I == N - 1 && "extracting subobject of scalar?");
2768 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002769 return handler.found(Index ? O->getComplexIntImag()
2770 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002771 } else {
2772 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002773 return handler.found(Index ? O->getComplexFloatImag()
2774 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002775 }
Richard Smithd62306a2011-11-10 06:34:14 +00002776 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002777 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002778 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002779 << Field;
2780 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002781 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002782 }
2783
Richard Smithd62306a2011-11-10 06:34:14 +00002784 // Next subobject is a class, struct or union field.
2785 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2786 if (RD->isUnion()) {
2787 const FieldDecl *UnionField = O->getUnionField();
2788 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002789 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002790 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002791 << handler.AccessKind << Field << !UnionField << UnionField;
2792 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002793 }
Richard Smithd62306a2011-11-10 06:34:14 +00002794 O = &O->getUnionValue();
2795 } else
2796 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002797
2798 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002799 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002800 if (WasConstQualified && !Field->isMutable())
2801 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002802
2803 if (ObjType.isVolatileQualified()) {
2804 if (Info.getLangOpts().CPlusPlus) {
2805 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002806 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002807 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002808 Info.Note(Field->getLocation(), diag::note_declared_at);
2809 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002810 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002811 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002812 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002813 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002814
2815 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002816 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002817 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002818 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2819 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2820 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002821
2822 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002823 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002824 if (WasConstQualified)
2825 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002826 }
2827 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002828}
2829
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002830namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002831struct ExtractSubobjectHandler {
2832 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002833 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002834
2835 static const AccessKinds AccessKind = AK_Read;
2836
2837 typedef bool result_type;
2838 bool failed() { return false; }
2839 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002840 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002841 return true;
2842 }
2843 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002844 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002845 return true;
2846 }
2847 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002848 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002849 return true;
2850 }
2851 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002852 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002853 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2854 return true;
2855 }
2856};
Richard Smith3229b742013-05-05 21:17:10 +00002857} // end anonymous namespace
2858
Richard Smith3da88fa2013-04-26 14:36:30 +00002859const AccessKinds ExtractSubobjectHandler::AccessKind;
2860
2861/// Extract the designated sub-object of an rvalue.
2862static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002863 const CompleteObject &Obj,
2864 const SubobjectDesignator &Sub,
2865 APValue &Result) {
2866 ExtractSubobjectHandler Handler = { Info, Result };
2867 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002868}
2869
Richard Smith3229b742013-05-05 21:17:10 +00002870namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002871struct ModifySubobjectHandler {
2872 EvalInfo &Info;
2873 APValue &NewVal;
2874 const Expr *E;
2875
2876 typedef bool result_type;
2877 static const AccessKinds AccessKind = AK_Assign;
2878
2879 bool checkConst(QualType QT) {
2880 // Assigning to a const object has undefined behavior.
2881 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002882 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002883 return false;
2884 }
2885 return true;
2886 }
2887
2888 bool failed() { return false; }
2889 bool found(APValue &Subobj, QualType SubobjType) {
2890 if (!checkConst(SubobjType))
2891 return false;
2892 // We've been given ownership of NewVal, so just swap it in.
2893 Subobj.swap(NewVal);
2894 return true;
2895 }
2896 bool found(APSInt &Value, QualType SubobjType) {
2897 if (!checkConst(SubobjType))
2898 return false;
2899 if (!NewVal.isInt()) {
2900 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002901 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002902 return false;
2903 }
2904 Value = NewVal.getInt();
2905 return true;
2906 }
2907 bool found(APFloat &Value, QualType SubobjType) {
2908 if (!checkConst(SubobjType))
2909 return false;
2910 Value = NewVal.getFloat();
2911 return true;
2912 }
2913 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2914 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2915 }
2916};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002917} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002918
Richard Smith3229b742013-05-05 21:17:10 +00002919const AccessKinds ModifySubobjectHandler::AccessKind;
2920
Richard Smith3da88fa2013-04-26 14:36:30 +00002921/// Update the designated sub-object of an rvalue to the given value.
2922static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002923 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002924 const SubobjectDesignator &Sub,
2925 APValue &NewVal) {
2926 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002927 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002928}
2929
Richard Smith84f6dcf2012-02-02 01:16:57 +00002930/// Find the position where two subobject designators diverge, or equivalently
2931/// the length of the common initial subsequence.
2932static unsigned FindDesignatorMismatch(QualType ObjType,
2933 const SubobjectDesignator &A,
2934 const SubobjectDesignator &B,
2935 bool &WasArrayIndex) {
2936 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2937 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002938 if (!ObjType.isNull() &&
2939 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002940 // Next subobject is an array element.
2941 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2942 WasArrayIndex = true;
2943 return I;
2944 }
Richard Smith66c96992012-02-18 22:04:06 +00002945 if (ObjType->isAnyComplexType())
2946 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2947 else
2948 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002949 } else {
2950 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2951 WasArrayIndex = false;
2952 return I;
2953 }
2954 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2955 // Next subobject is a field.
2956 ObjType = FD->getType();
2957 else
2958 // Next subobject is a base class.
2959 ObjType = QualType();
2960 }
2961 }
2962 WasArrayIndex = false;
2963 return I;
2964}
2965
2966/// Determine whether the given subobject designators refer to elements of the
2967/// same array object.
2968static bool AreElementsOfSameArray(QualType ObjType,
2969 const SubobjectDesignator &A,
2970 const SubobjectDesignator &B) {
2971 if (A.Entries.size() != B.Entries.size())
2972 return false;
2973
George Burgess IVa51c4072015-10-16 01:49:01 +00002974 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002975 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2976 // A is a subobject of the array element.
2977 return false;
2978
2979 // If A (and B) designates an array element, the last entry will be the array
2980 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2981 // of length 1' case, and the entire path must match.
2982 bool WasArrayIndex;
2983 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2984 return CommonLength >= A.Entries.size() - IsArray;
2985}
2986
Richard Smith3229b742013-05-05 21:17:10 +00002987/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002988static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2989 AccessKinds AK, const LValue &LVal,
2990 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002991 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002992 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002993 return CompleteObject();
2994 }
2995
Craig Topper36250ad2014-05-12 05:36:57 +00002996 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002997 if (LVal.CallIndex) {
2998 Frame = Info.getCallFrame(LVal.CallIndex);
2999 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003000 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003001 << AK << LVal.Base.is<const ValueDecl*>();
3002 NoteLValueLocation(Info, LVal.Base);
3003 return CompleteObject();
3004 }
Richard Smith3229b742013-05-05 21:17:10 +00003005 }
3006
3007 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3008 // is not a constant expression (even if the object is non-volatile). We also
3009 // apply this rule to C++98, in order to conform to the expected 'volatile'
3010 // semantics.
3011 if (LValType.isVolatileQualified()) {
3012 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003013 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003014 << AK << LValType;
3015 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003016 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003017 return CompleteObject();
3018 }
3019
3020 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003021 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003022 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00003023
3024 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3025 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3026 // In C++11, constexpr, non-volatile variables initialized with constant
3027 // expressions are constant expressions too. Inside constexpr functions,
3028 // parameters are constant expressions even if they're non-const.
3029 // In C++1y, objects local to a constant expression (those with a Frame) are
3030 // both readable and writable inside constant expressions.
3031 // In C, such things can also be folded, although they are not ICEs.
3032 const VarDecl *VD = dyn_cast<VarDecl>(D);
3033 if (VD) {
3034 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3035 VD = VDef;
3036 }
3037 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003038 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003039 return CompleteObject();
3040 }
3041
3042 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003043 if (BaseType.isVolatileQualified()) {
3044 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003045 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003046 << AK << 1 << VD;
3047 Info.Note(VD->getLocation(), diag::note_declared_at);
3048 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003049 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003050 }
3051 return CompleteObject();
3052 }
3053
3054 // Unless we're looking at a local variable or argument in a constexpr call,
3055 // the variable we're reading must be const.
3056 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003057 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003058 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3059 // OK, we can read and modify an object if we're in the process of
3060 // evaluating its initializer, because its lifetime began in this
3061 // evaluation.
3062 } else if (AK != AK_Read) {
3063 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003064 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003065 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003066 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003067 // OK, we can read this variable.
3068 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003069 // In OpenCL if a variable is in constant address space it is a const value.
3070 if (!(BaseType.isConstQualified() ||
3071 (Info.getLangOpts().OpenCL &&
3072 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003073 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003074 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003075 Info.Note(VD->getLocation(), diag::note_declared_at);
3076 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003077 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003078 }
3079 return CompleteObject();
3080 }
3081 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3082 // We support folding of const floating-point types, in order to make
3083 // static const data members of such types (supported as an extension)
3084 // more useful.
3085 if (Info.getLangOpts().CPlusPlus11) {
3086 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3087 Info.Note(VD->getLocation(), diag::note_declared_at);
3088 } else {
3089 Info.CCEDiag(E);
3090 }
George Burgess IVb5316982016-12-27 05:33:20 +00003091 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3092 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3093 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003094 } else {
3095 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003096 if (Info.checkingPotentialConstantExpression() &&
3097 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3098 // The definition of this variable could be constexpr. We can't
3099 // access it right now, but may be able to in future.
3100 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003101 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003102 Info.Note(VD->getLocation(), diag::note_declared_at);
3103 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003104 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003105 }
3106 return CompleteObject();
3107 }
3108 }
3109
3110 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3111 return CompleteObject();
3112 } else {
3113 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3114
3115 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003116 if (const MaterializeTemporaryExpr *MTE =
3117 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3118 assert(MTE->getStorageDuration() == SD_Static &&
3119 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003120
Richard Smithe6c01442013-06-05 00:46:14 +00003121 // Per C++1y [expr.const]p2:
3122 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3123 // - a [...] glvalue of integral or enumeration type that refers to
3124 // a non-volatile const object [...]
3125 // [...]
3126 // - a [...] glvalue of literal type that refers to a non-volatile
3127 // object whose lifetime began within the evaluation of e.
3128 //
3129 // C++11 misses the 'began within the evaluation of e' check and
3130 // instead allows all temporaries, including things like:
3131 // int &&r = 1;
3132 // int x = ++r;
3133 // constexpr int k = r;
3134 // Therefore we use the C++1y rules in C++11 too.
3135 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3136 const ValueDecl *ED = MTE->getExtendingDecl();
3137 if (!(BaseType.isConstQualified() &&
3138 BaseType->isIntegralOrEnumerationType()) &&
3139 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003140 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003141 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3142 return CompleteObject();
3143 }
3144
3145 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3146 assert(BaseVal && "got reference to unevaluated temporary");
3147 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003148 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003149 return CompleteObject();
3150 }
3151 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003152 BaseVal = Frame->getTemporary(Base);
3153 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003154 }
Richard Smith3229b742013-05-05 21:17:10 +00003155
3156 // Volatile temporary objects cannot be accessed in constant expressions.
3157 if (BaseType.isVolatileQualified()) {
3158 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003159 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003160 << AK << 0;
3161 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3162 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003163 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003164 }
3165 return CompleteObject();
3166 }
3167 }
3168
Richard Smith7525ff62013-05-09 07:14:00 +00003169 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003170 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003171 // object under construction.
Erik Pilkington42925492017-10-04 00:18:55 +00003172 if (Info.isEvaluatingConstructor(LVal.getLValueBase(), LVal.CallIndex)) {
Richard Smith7525ff62013-05-09 07:14:00 +00003173 BaseType = Info.Ctx.getCanonicalType(BaseType);
3174 BaseType.removeLocalConst();
3175 }
3176
Richard Smith6d4c6582013-11-05 22:18:15 +00003177 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003178 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003179 //
3180 // FIXME: Not all local state is mutable. Allow local constant subobjects
3181 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003182 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3183 Info.EvalStatus.HasSideEffects) ||
3184 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003185 return CompleteObject();
3186
3187 return CompleteObject(BaseVal, BaseType);
3188}
3189
Richard Smith243ef902013-05-05 23:31:59 +00003190/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3191/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3192/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003193///
3194/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003195/// \param Conv - The expression for which we are performing the conversion.
3196/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003197/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3198/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003199/// \param LVal - The glvalue on which we are attempting to perform this action.
3200/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003201static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003202 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003203 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003204 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003205 return false;
3206
Richard Smith3229b742013-05-05 21:17:10 +00003207 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003208 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003209 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003210 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3211 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3212 // initializer until now for such expressions. Such an expression can't be
3213 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003214 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003215 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003216 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003217 }
Richard Smith3229b742013-05-05 21:17:10 +00003218 APValue Lit;
3219 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3220 return false;
3221 CompleteObject LitObj(&Lit, Base->getType());
3222 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003223 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003224 // We represent a string literal array as an lvalue pointing at the
3225 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003226 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003227 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3228 CompleteObject StrObj(&Str, Base->getType());
3229 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003230 }
Richard Smith11562c52011-10-28 17:51:58 +00003231 }
3232
Richard Smith3229b742013-05-05 21:17:10 +00003233 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3234 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003235}
3236
3237/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003238static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003239 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003240 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003241 return false;
3242
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003243 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003244 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003245 return false;
3246 }
3247
Richard Smith3229b742013-05-05 21:17:10 +00003248 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Aaron Ballmana5038552018-01-09 13:07:03 +00003249 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3250}
3251
3252namespace {
3253struct CompoundAssignSubobjectHandler {
3254 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003255 const Expr *E;
3256 QualType PromotedLHSType;
3257 BinaryOperatorKind Opcode;
3258 const APValue &RHS;
3259
3260 static const AccessKinds AccessKind = AK_Assign;
3261
3262 typedef bool result_type;
3263
3264 bool checkConst(QualType QT) {
3265 // Assigning to a const object has undefined behavior.
3266 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003267 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003268 return false;
3269 }
3270 return true;
3271 }
3272
3273 bool failed() { return false; }
3274 bool found(APValue &Subobj, QualType SubobjType) {
3275 switch (Subobj.getKind()) {
3276 case APValue::Int:
3277 return found(Subobj.getInt(), SubobjType);
3278 case APValue::Float:
3279 return found(Subobj.getFloat(), SubobjType);
3280 case APValue::ComplexInt:
3281 case APValue::ComplexFloat:
3282 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003283 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003284 return false;
3285 case APValue::LValue:
3286 return foundPointer(Subobj, SubobjType);
3287 default:
3288 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003289 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003290 return false;
3291 }
3292 }
3293 bool found(APSInt &Value, QualType SubobjType) {
3294 if (!checkConst(SubobjType))
3295 return false;
3296
3297 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3298 // We don't support compound assignment on integer-cast-to-pointer
3299 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003300 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003301 return false;
3302 }
3303
3304 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3305 SubobjType, Value);
3306 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3307 return false;
3308 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3309 return true;
3310 }
3311 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003312 return checkConst(SubobjType) &&
3313 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3314 Value) &&
3315 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3316 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003317 }
3318 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3319 if (!checkConst(SubobjType))
3320 return false;
3321
3322 QualType PointeeType;
3323 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3324 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003325
3326 if (PointeeType.isNull() || !RHS.isInt() ||
3327 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003328 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003329 return false;
3330 }
3331
Richard Smithd6cc1982017-01-31 02:23:02 +00003332 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003333 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003334 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003335
3336 LValue LVal;
3337 LVal.setFrom(Info.Ctx, Subobj);
3338 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3339 return false;
3340 LVal.moveInto(Subobj);
3341 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003342 }
3343 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3344 llvm_unreachable("shouldn't encounter string elements here");
3345 }
3346};
3347} // end anonymous namespace
3348
3349const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3350
3351/// Perform a compound assignment of LVal <op>= RVal.
3352static bool handleCompoundAssignment(
3353 EvalInfo &Info, const Expr *E,
3354 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3355 BinaryOperatorKind Opcode, const APValue &RVal) {
3356 if (LVal.Designator.Invalid)
3357 return false;
3358
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003359 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003360 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003361 return false;
3362 }
3363
3364 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3365 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3366 RVal };
3367 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3368}
3369
Aaron Ballmana5038552018-01-09 13:07:03 +00003370namespace {
3371struct IncDecSubobjectHandler {
3372 EvalInfo &Info;
3373 const UnaryOperator *E;
3374 AccessKinds AccessKind;
3375 APValue *Old;
3376
Richard Smith243ef902013-05-05 23:31:59 +00003377 typedef bool result_type;
3378
3379 bool checkConst(QualType QT) {
3380 // Assigning to a const object has undefined behavior.
3381 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003382 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003383 return false;
3384 }
3385 return true;
3386 }
3387
3388 bool failed() { return false; }
3389 bool found(APValue &Subobj, QualType SubobjType) {
3390 // Stash the old value. Also clear Old, so we don't clobber it later
3391 // if we're post-incrementing a complex.
3392 if (Old) {
3393 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003394 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003395 }
3396
3397 switch (Subobj.getKind()) {
3398 case APValue::Int:
3399 return found(Subobj.getInt(), SubobjType);
3400 case APValue::Float:
3401 return found(Subobj.getFloat(), SubobjType);
3402 case APValue::ComplexInt:
3403 return found(Subobj.getComplexIntReal(),
3404 SubobjType->castAs<ComplexType>()->getElementType()
3405 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3406 case APValue::ComplexFloat:
3407 return found(Subobj.getComplexFloatReal(),
3408 SubobjType->castAs<ComplexType>()->getElementType()
3409 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3410 case APValue::LValue:
3411 return foundPointer(Subobj, SubobjType);
3412 default:
3413 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003414 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003415 return false;
3416 }
3417 }
3418 bool found(APSInt &Value, QualType SubobjType) {
3419 if (!checkConst(SubobjType))
3420 return false;
3421
3422 if (!SubobjType->isIntegerType()) {
3423 // We don't support increment / decrement on integer-cast-to-pointer
3424 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003425 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003426 return false;
3427 }
3428
3429 if (Old) *Old = APValue(Value);
3430
3431 // bool arithmetic promotes to int, and the conversion back to bool
3432 // doesn't reduce mod 2^n, so special-case it.
3433 if (SubobjType->isBooleanType()) {
3434 if (AccessKind == AK_Increment)
3435 Value = 1;
3436 else
3437 Value = !Value;
3438 return true;
3439 }
3440
3441 bool WasNegative = Value.isNegative();
Aaron Ballmana5038552018-01-09 13:07:03 +00003442 if (AccessKind == AK_Increment) {
3443 ++Value;
3444
3445 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3446 APSInt ActualValue(Value, /*IsUnsigned*/true);
3447 return HandleOverflow(Info, E, ActualValue, SubobjType);
3448 }
3449 } else {
3450 --Value;
3451
3452 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3453 unsigned BitWidth = Value.getBitWidth();
3454 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3455 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003456 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003457 }
3458 }
3459 return true;
3460 }
3461 bool found(APFloat &Value, QualType SubobjType) {
3462 if (!checkConst(SubobjType))
3463 return false;
3464
3465 if (Old) *Old = APValue(Value);
3466
3467 APFloat One(Value.getSemantics(), 1);
3468 if (AccessKind == AK_Increment)
3469 Value.add(One, APFloat::rmNearestTiesToEven);
3470 else
3471 Value.subtract(One, APFloat::rmNearestTiesToEven);
3472 return true;
3473 }
3474 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3475 if (!checkConst(SubobjType))
3476 return false;
3477
3478 QualType PointeeType;
3479 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3480 PointeeType = PT->getPointeeType();
3481 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003482 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003483 return false;
3484 }
3485
3486 LValue LVal;
3487 LVal.setFrom(Info.Ctx, Subobj);
3488 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3489 AccessKind == AK_Increment ? 1 : -1))
3490 return false;
3491 LVal.moveInto(Subobj);
3492 return true;
3493 }
3494 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3495 llvm_unreachable("shouldn't encounter string elements here");
3496 }
3497};
3498} // end anonymous namespace
3499
3500/// Perform an increment or decrement on LVal.
3501static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3502 QualType LValType, bool IsIncrement, APValue *Old) {
3503 if (LVal.Designator.Invalid)
3504 return false;
3505
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003506 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003507 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003508 return false;
3509 }
Aaron Ballmana5038552018-01-09 13:07:03 +00003510
3511 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3512 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3513 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3514 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3515}
3516
Richard Smithe97cbd72011-11-11 04:05:33 +00003517/// Build an lvalue for the object argument of a member function call.
3518static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3519 LValue &This) {
3520 if (Object->getType()->isPointerType())
3521 return EvaluatePointer(Object, This, Info);
3522
3523 if (Object->isGLValue())
3524 return EvaluateLValue(Object, This, Info);
3525
Richard Smithd9f663b2013-04-22 15:31:51 +00003526 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003527 return EvaluateTemporary(Object, This, Info);
3528
Faisal Valie690b7a2016-07-02 22:34:24 +00003529 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003530 return false;
3531}
3532
3533/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3534/// lvalue referring to the result.
3535///
3536/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003537/// \param LV - An lvalue referring to the base of the member pointer.
3538/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003539/// \param IncludeMember - Specifies whether the member itself is included in
3540/// the resulting LValue subobject designator. This is not possible when
3541/// creating a bound member function.
3542/// \return The field or method declaration to which the member pointer refers,
3543/// or 0 if evaluation fails.
3544static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003545 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003546 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003547 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003548 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003549 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003550 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003551 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003552
3553 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3554 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003555 if (!MemPtr.getDecl()) {
3556 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003557 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003558 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003559 }
Richard Smith253c2a32012-01-27 01:14:48 +00003560
Richard Smith027bf112011-11-17 22:56:20 +00003561 if (MemPtr.isDerivedMember()) {
3562 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003563 // The end of the derived-to-base path for the base object must match the
3564 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003565 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003566 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003567 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003568 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003569 }
Richard Smith027bf112011-11-17 22:56:20 +00003570 unsigned PathLengthToMember =
3571 LV.Designator.Entries.size() - MemPtr.Path.size();
3572 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3573 const CXXRecordDecl *LVDecl = getAsBaseClass(
3574 LV.Designator.Entries[PathLengthToMember + I]);
3575 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003576 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003577 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003578 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003579 }
Richard Smith027bf112011-11-17 22:56:20 +00003580 }
3581
3582 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003583 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003584 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003585 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003586 } else if (!MemPtr.Path.empty()) {
3587 // Extend the LValue path with the member pointer's path.
3588 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3589 MemPtr.Path.size() + IncludeMember);
3590
3591 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003592 if (const PointerType *PT = LVType->getAs<PointerType>())
3593 LVType = PT->getPointeeType();
3594 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3595 assert(RD && "member pointer access on non-class-type expression");
3596 // The first class in the path is that of the lvalue.
3597 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3598 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003599 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003600 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003601 RD = Base;
3602 }
3603 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003604 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3605 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003606 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003607 }
3608
3609 // Add the member. Note that we cannot build bound member functions here.
3610 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003611 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003612 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003613 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003614 } else if (const IndirectFieldDecl *IFD =
3615 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003616 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003617 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003618 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003619 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003620 }
Richard Smith027bf112011-11-17 22:56:20 +00003621 }
3622
3623 return MemPtr.getDecl();
3624}
3625
Richard Smith84401042013-06-03 05:03:02 +00003626static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3627 const BinaryOperator *BO,
3628 LValue &LV,
3629 bool IncludeMember = true) {
3630 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3631
3632 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003633 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003634 MemberPtr MemPtr;
3635 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3636 }
Craig Topper36250ad2014-05-12 05:36:57 +00003637 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003638 }
3639
3640 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3641 BO->getRHS(), IncludeMember);
3642}
3643
Richard Smith027bf112011-11-17 22:56:20 +00003644/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3645/// the provided lvalue, which currently refers to the base object.
3646static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3647 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003648 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003649 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003650 return false;
3651
Richard Smitha8105bc2012-01-06 16:39:00 +00003652 QualType TargetQT = E->getType();
3653 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3654 TargetQT = PT->getPointeeType();
3655
3656 // Check this cast lands within the final derived-to-base subobject path.
3657 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003658 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003659 << D.MostDerivedType << TargetQT;
3660 return false;
3661 }
3662
Richard Smith027bf112011-11-17 22:56:20 +00003663 // Check the type of the final cast. We don't need to check the path,
3664 // since a cast can only be formed if the path is unique.
3665 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003666 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3667 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003668 if (NewEntriesSize == D.MostDerivedPathLength)
3669 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3670 else
Richard Smith027bf112011-11-17 22:56:20 +00003671 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003672 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003673 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003674 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003675 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003676 }
Richard Smith027bf112011-11-17 22:56:20 +00003677
3678 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003679 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003680}
3681
Mike Stump876387b2009-10-27 22:09:17 +00003682namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003683enum EvalStmtResult {
3684 /// Evaluation failed.
3685 ESR_Failed,
3686 /// Hit a 'return' statement.
3687 ESR_Returned,
3688 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003689 ESR_Succeeded,
3690 /// Hit a 'continue' statement.
3691 ESR_Continue,
3692 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003693 ESR_Break,
3694 /// Still scanning for 'case' or 'default' statement.
3695 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003696};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003697}
Richard Smith254a73d2011-10-28 22:34:42 +00003698
Richard Smith97fcf4b2016-08-14 23:15:52 +00003699static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3700 // We don't need to evaluate the initializer for a static local.
3701 if (!VD->hasLocalStorage())
3702 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003703
Richard Smith97fcf4b2016-08-14 23:15:52 +00003704 LValue Result;
3705 Result.set(VD, Info.CurrentCall->Index);
3706 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003707
Richard Smith97fcf4b2016-08-14 23:15:52 +00003708 const Expr *InitE = VD->getInit();
3709 if (!InitE) {
3710 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3711 << false << VD->getType();
3712 Val = APValue();
3713 return false;
3714 }
Richard Smith51f03172013-06-20 03:00:05 +00003715
Richard Smith97fcf4b2016-08-14 23:15:52 +00003716 if (InitE->isValueDependent())
3717 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003718
Richard Smith97fcf4b2016-08-14 23:15:52 +00003719 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3720 // Wipe out any partially-computed value, to allow tracking that this
3721 // evaluation failed.
3722 Val = APValue();
3723 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003724 }
3725
3726 return true;
3727}
3728
Richard Smith97fcf4b2016-08-14 23:15:52 +00003729static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3730 bool OK = true;
3731
3732 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3733 OK &= EvaluateVarDecl(Info, VD);
3734
3735 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3736 for (auto *BD : DD->bindings())
3737 if (auto *VD = BD->getHoldingVar())
3738 OK &= EvaluateDecl(Info, VD);
3739
3740 return OK;
3741}
3742
3743
Richard Smith4e18ca52013-05-06 05:56:11 +00003744/// Evaluate a condition (either a variable declaration or an expression).
3745static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3746 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003747 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003748 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3749 return false;
3750 return EvaluateAsBooleanCondition(Cond, Result, Info);
3751}
3752
Richard Smith89210072016-04-04 23:29:43 +00003753namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003754/// \brief A location where the result (returned value) of evaluating a
3755/// statement should be stored.
3756struct StmtResult {
3757 /// The APValue that should be filled in with the returned value.
3758 APValue &Value;
3759 /// The location containing the result, if any (used to support RVO).
3760 const LValue *Slot;
3761};
Richard Smith89210072016-04-04 23:29:43 +00003762}
Richard Smith52a980a2015-08-28 02:43:42 +00003763
3764static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003765 const Stmt *S,
3766 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003767
3768/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003769static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003770 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003771 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003772 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003773 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003774 case ESR_Break:
3775 return ESR_Succeeded;
3776 case ESR_Succeeded:
3777 case ESR_Continue:
3778 return ESR_Continue;
3779 case ESR_Failed:
3780 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003781 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003782 return ESR;
3783 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003784 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003785}
3786
Richard Smith496ddcf2013-05-12 17:32:42 +00003787/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003788static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003789 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003790 BlockScopeRAII Scope(Info);
3791
Richard Smith496ddcf2013-05-12 17:32:42 +00003792 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003793 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003794 {
3795 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003796 if (const Stmt *Init = SS->getInit()) {
3797 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3798 if (ESR != ESR_Succeeded)
3799 return ESR;
3800 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003801 if (SS->getConditionVariable() &&
3802 !EvaluateDecl(Info, SS->getConditionVariable()))
3803 return ESR_Failed;
3804 if (!EvaluateInteger(SS->getCond(), Value, Info))
3805 return ESR_Failed;
3806 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003807
3808 // Find the switch case corresponding to the value of the condition.
3809 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003810 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003811 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3812 SC = SC->getNextSwitchCase()) {
3813 if (isa<DefaultStmt>(SC)) {
3814 Found = SC;
3815 continue;
3816 }
3817
3818 const CaseStmt *CS = cast<CaseStmt>(SC);
3819 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3820 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3821 : LHS;
3822 if (LHS <= Value && Value <= RHS) {
3823 Found = SC;
3824 break;
3825 }
3826 }
3827
3828 if (!Found)
3829 return ESR_Succeeded;
3830
3831 // Search the switch body for the switch case and evaluate it from there.
3832 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3833 case ESR_Break:
3834 return ESR_Succeeded;
3835 case ESR_Succeeded:
3836 case ESR_Continue:
3837 case ESR_Failed:
3838 case ESR_Returned:
3839 return ESR;
3840 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003841 // This can only happen if the switch case is nested within a statement
3842 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003843 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003844 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003845 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003846 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003847}
3848
Richard Smith254a73d2011-10-28 22:34:42 +00003849// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003850static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003851 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003852 if (!Info.nextStep(S))
3853 return ESR_Failed;
3854
Richard Smith496ddcf2013-05-12 17:32:42 +00003855 // If we're hunting down a 'case' or 'default' label, recurse through
3856 // substatements until we hit the label.
3857 if (Case) {
3858 // FIXME: We don't start the lifetime of objects whose initialization we
3859 // jump over. However, such objects must be of class type with a trivial
3860 // default constructor that initialize all subobjects, so must be empty,
3861 // so this almost never matters.
3862 switch (S->getStmtClass()) {
3863 case Stmt::CompoundStmtClass:
3864 // FIXME: Precompute which substatement of a compound statement we
3865 // would jump to, and go straight there rather than performing a
3866 // linear scan each time.
3867 case Stmt::LabelStmtClass:
3868 case Stmt::AttributedStmtClass:
3869 case Stmt::DoStmtClass:
3870 break;
3871
3872 case Stmt::CaseStmtClass:
3873 case Stmt::DefaultStmtClass:
3874 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003875 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003876 break;
3877
3878 case Stmt::IfStmtClass: {
3879 // FIXME: Precompute which side of an 'if' we would jump to, and go
3880 // straight there rather than scanning both sides.
3881 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003882
3883 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3884 // preceded by our switch label.
3885 BlockScopeRAII Scope(Info);
3886
Richard Smith496ddcf2013-05-12 17:32:42 +00003887 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3888 if (ESR != ESR_CaseNotFound || !IS->getElse())
3889 return ESR;
3890 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3891 }
3892
3893 case Stmt::WhileStmtClass: {
3894 EvalStmtResult ESR =
3895 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3896 if (ESR != ESR_Continue)
3897 return ESR;
3898 break;
3899 }
3900
3901 case Stmt::ForStmtClass: {
3902 const ForStmt *FS = cast<ForStmt>(S);
3903 EvalStmtResult ESR =
3904 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3905 if (ESR != ESR_Continue)
3906 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003907 if (FS->getInc()) {
3908 FullExpressionRAII IncScope(Info);
3909 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3910 return ESR_Failed;
3911 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003912 break;
3913 }
3914
3915 case Stmt::DeclStmtClass:
3916 // FIXME: If the variable has initialization that can't be jumped over,
3917 // bail out of any immediately-surrounding compound-statement too.
3918 default:
3919 return ESR_CaseNotFound;
3920 }
3921 }
3922
Richard Smith254a73d2011-10-28 22:34:42 +00003923 switch (S->getStmtClass()) {
3924 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003925 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003926 // Don't bother evaluating beyond an expression-statement which couldn't
3927 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003928 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003929 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003930 return ESR_Failed;
3931 return ESR_Succeeded;
3932 }
3933
Faisal Valie690b7a2016-07-02 22:34:24 +00003934 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003935 return ESR_Failed;
3936
3937 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003938 return ESR_Succeeded;
3939
Richard Smithd9f663b2013-04-22 15:31:51 +00003940 case Stmt::DeclStmtClass: {
3941 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003942 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003943 // Each declaration initialization is its own full-expression.
3944 // FIXME: This isn't quite right; if we're performing aggregate
3945 // initialization, each braced subexpression is its own full-expression.
3946 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003947 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003948 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003949 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003950 return ESR_Succeeded;
3951 }
3952
Richard Smith357362d2011-12-13 06:39:58 +00003953 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003954 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003955 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003956 if (RetExpr &&
3957 !(Result.Slot
3958 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3959 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003960 return ESR_Failed;
3961 return ESR_Returned;
3962 }
Richard Smith254a73d2011-10-28 22:34:42 +00003963
3964 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003965 BlockScopeRAII Scope(Info);
3966
Richard Smith254a73d2011-10-28 22:34:42 +00003967 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003968 for (const auto *BI : CS->body()) {
3969 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003970 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003971 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003972 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003973 return ESR;
3974 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003975 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003976 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003977
3978 case Stmt::IfStmtClass: {
3979 const IfStmt *IS = cast<IfStmt>(S);
3980
3981 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003982 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003983 if (const Stmt *Init = IS->getInit()) {
3984 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3985 if (ESR != ESR_Succeeded)
3986 return ESR;
3987 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003988 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003989 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003990 return ESR_Failed;
3991
3992 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3993 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3994 if (ESR != ESR_Succeeded)
3995 return ESR;
3996 }
3997 return ESR_Succeeded;
3998 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003999
4000 case Stmt::WhileStmtClass: {
4001 const WhileStmt *WS = cast<WhileStmt>(S);
4002 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004003 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004004 bool Continue;
4005 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4006 Continue))
4007 return ESR_Failed;
4008 if (!Continue)
4009 break;
4010
4011 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4012 if (ESR != ESR_Continue)
4013 return ESR;
4014 }
4015 return ESR_Succeeded;
4016 }
4017
4018 case Stmt::DoStmtClass: {
4019 const DoStmt *DS = cast<DoStmt>(S);
4020 bool Continue;
4021 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004022 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004023 if (ESR != ESR_Continue)
4024 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004025 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004026
Richard Smith08d6a2c2013-07-24 07:11:57 +00004027 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004028 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4029 return ESR_Failed;
4030 } while (Continue);
4031 return ESR_Succeeded;
4032 }
4033
4034 case Stmt::ForStmtClass: {
4035 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004036 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004037 if (FS->getInit()) {
4038 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4039 if (ESR != ESR_Succeeded)
4040 return ESR;
4041 }
4042 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004043 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004044 bool Continue = true;
4045 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4046 FS->getCond(), Continue))
4047 return ESR_Failed;
4048 if (!Continue)
4049 break;
4050
4051 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4052 if (ESR != ESR_Continue)
4053 return ESR;
4054
Richard Smith08d6a2c2013-07-24 07:11:57 +00004055 if (FS->getInc()) {
4056 FullExpressionRAII IncScope(Info);
4057 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4058 return ESR_Failed;
4059 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004060 }
4061 return ESR_Succeeded;
4062 }
4063
Richard Smith896e0d72013-05-06 06:51:17 +00004064 case Stmt::CXXForRangeStmtClass: {
4065 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004066 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004067
4068 // Initialize the __range variable.
4069 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4070 if (ESR != ESR_Succeeded)
4071 return ESR;
4072
4073 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004074 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4075 if (ESR != ESR_Succeeded)
4076 return ESR;
4077 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004078 if (ESR != ESR_Succeeded)
4079 return ESR;
4080
4081 while (true) {
4082 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004083 {
4084 bool Continue = true;
4085 FullExpressionRAII CondExpr(Info);
4086 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4087 return ESR_Failed;
4088 if (!Continue)
4089 break;
4090 }
Richard Smith896e0d72013-05-06 06:51:17 +00004091
4092 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004093 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004094 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4095 if (ESR != ESR_Succeeded)
4096 return ESR;
4097
4098 // Loop body.
4099 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4100 if (ESR != ESR_Continue)
4101 return ESR;
4102
4103 // Increment: ++__begin
4104 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4105 return ESR_Failed;
4106 }
4107
4108 return ESR_Succeeded;
4109 }
4110
Richard Smith496ddcf2013-05-12 17:32:42 +00004111 case Stmt::SwitchStmtClass:
4112 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4113
Richard Smith4e18ca52013-05-06 05:56:11 +00004114 case Stmt::ContinueStmtClass:
4115 return ESR_Continue;
4116
4117 case Stmt::BreakStmtClass:
4118 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004119
4120 case Stmt::LabelStmtClass:
4121 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4122
4123 case Stmt::AttributedStmtClass:
4124 // As a general principle, C++11 attributes can be ignored without
4125 // any semantic impact.
4126 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4127 Case);
4128
4129 case Stmt::CaseStmtClass:
4130 case Stmt::DefaultStmtClass:
4131 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004132 }
4133}
4134
Richard Smithcc36f692011-12-22 02:22:31 +00004135/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4136/// default constructor. If so, we'll fold it whether or not it's marked as
4137/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4138/// so we need special handling.
4139static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004140 const CXXConstructorDecl *CD,
4141 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004142 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4143 return false;
4144
Richard Smith66e05fe2012-01-18 05:21:49 +00004145 // Value-initialization does not call a trivial default constructor, so such a
4146 // call is a core constant expression whether or not the constructor is
4147 // constexpr.
4148 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004149 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004150 // FIXME: If DiagDecl is an implicitly-declared special member function,
4151 // we should be much more explicit about why it's not constexpr.
4152 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4153 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4154 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004155 } else {
4156 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4157 }
4158 }
4159 return true;
4160}
4161
Richard Smith357362d2011-12-13 06:39:58 +00004162/// CheckConstexprFunction - Check that a function can be called in a constant
4163/// expression.
4164static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4165 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004166 const FunctionDecl *Definition,
4167 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004168 // Potential constant expressions can contain calls to declared, but not yet
4169 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004170 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004171 Declaration->isConstexpr())
4172 return false;
4173
Richard Smith0838f3a2013-05-14 05:18:44 +00004174 // Bail out with no diagnostic if the function declaration itself is invalid.
4175 // We will have produced a relevant diagnostic while parsing it.
4176 if (Declaration->isInvalidDecl())
4177 return false;
4178
Richard Smith357362d2011-12-13 06:39:58 +00004179 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004180 if (Definition && Definition->isConstexpr() &&
4181 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004182 return true;
4183
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004184 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004185 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Daniel Jasperffdee092017-05-02 19:21:42 +00004186
Richard Smith5179eb72016-06-28 19:03:57 +00004187 // If this function is not constexpr because it is an inherited
4188 // non-constexpr constructor, diagnose that directly.
4189 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4190 if (CD && CD->isInheritingConstructor()) {
4191 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Daniel Jasperffdee092017-05-02 19:21:42 +00004192 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004193 DiagDecl = CD = Inherited;
4194 }
4195
4196 // FIXME: If DiagDecl is an implicitly-declared special member function
4197 // or an inheriting constructor, we should be much more explicit about why
4198 // it's not constexpr.
4199 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004200 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004201 << CD->getInheritedConstructor().getConstructor()->getParent();
4202 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004203 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004204 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004205 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4206 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004207 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004208 }
4209 return false;
4210}
4211
Richard Smithbe6dd812014-11-19 21:27:17 +00004212/// Determine if a class has any fields that might need to be copied by a
4213/// trivial copy or move operation.
4214static bool hasFields(const CXXRecordDecl *RD) {
4215 if (!RD || RD->isEmpty())
4216 return false;
4217 for (auto *FD : RD->fields()) {
4218 if (FD->isUnnamedBitfield())
4219 continue;
4220 return true;
4221 }
4222 for (auto &Base : RD->bases())
4223 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4224 return true;
4225 return false;
4226}
4227
Richard Smithd62306a2011-11-10 06:34:14 +00004228namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004229typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004230}
4231
4232/// EvaluateArgs - Evaluate the arguments to a function call.
4233static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4234 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004235 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004236 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004237 I != E; ++I) {
4238 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4239 // If we're checking for a potential constant expression, evaluate all
4240 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004241 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004242 return false;
4243 Success = false;
4244 }
4245 }
4246 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004247}
4248
Richard Smith254a73d2011-10-28 22:34:42 +00004249/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004250static bool HandleFunctionCall(SourceLocation CallLoc,
4251 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004252 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004253 EvalInfo &Info, APValue &Result,
4254 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004255 ArgVector ArgValues(Args.size());
4256 if (!EvaluateArgs(Args, ArgValues, Info))
4257 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004258
Richard Smith253c2a32012-01-27 01:14:48 +00004259 if (!Info.CheckCallLimit(CallLoc))
4260 return false;
4261
4262 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004263
4264 // For a trivial copy or move assignment, perform an APValue copy. This is
4265 // essential for unions, where the operations performed by the assignment
4266 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004267 //
4268 // Skip this for non-union classes with no fields; in that case, the defaulted
4269 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004270 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004271 if (MD && MD->isDefaulted() &&
4272 (MD->getParent()->isUnion() ||
4273 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004274 assert(This &&
4275 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4276 LValue RHS;
4277 RHS.setFrom(Info.Ctx, ArgValues[0]);
4278 APValue RHSValue;
4279 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4280 RHS, RHSValue))
4281 return false;
4282 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4283 RHSValue))
4284 return false;
4285 This->moveInto(Result);
4286 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004287 } else if (MD && isLambdaCallOperator(MD)) {
4288 // We're in a lambda; determine the lambda capture field maps.
4289 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4290 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004291 }
4292
Richard Smith52a980a2015-08-28 02:43:42 +00004293 StmtResult Ret = {Result, ResultSlot};
4294 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004295 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004296 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004297 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004298 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004299 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004300 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004301}
4302
Richard Smithd62306a2011-11-10 06:34:14 +00004303/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004304static bool HandleConstructorCall(const Expr *E, const LValue &This,
4305 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004306 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004307 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004308 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004309 if (!Info.CheckCallLimit(CallLoc))
4310 return false;
4311
Richard Smith3607ffe2012-02-13 03:54:03 +00004312 const CXXRecordDecl *RD = Definition->getParent();
4313 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004314 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004315 return false;
4316 }
4317
Erik Pilkington42925492017-10-04 00:18:55 +00004318 EvalInfo::EvaluatingConstructorRAII EvalObj(
4319 Info, {This.getLValueBase(), This.CallIndex});
Richard Smith5179eb72016-06-28 19:03:57 +00004320 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004321
Richard Smith52a980a2015-08-28 02:43:42 +00004322 // FIXME: Creating an APValue just to hold a nonexistent return value is
4323 // wasteful.
4324 APValue RetVal;
4325 StmtResult Ret = {RetVal, nullptr};
4326
Richard Smith5179eb72016-06-28 19:03:57 +00004327 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004328 if (Definition->isDelegatingConstructor()) {
4329 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004330 {
4331 FullExpressionRAII InitScope(Info);
4332 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4333 return false;
4334 }
Richard Smith52a980a2015-08-28 02:43:42 +00004335 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004336 }
4337
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004338 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004339 // essential for unions (or classes with anonymous union members), where the
4340 // operations performed by the constructor cannot be represented by
4341 // ctor-initializers.
4342 //
4343 // Skip this for empty non-union classes; we should not perform an
4344 // lvalue-to-rvalue conversion on them because their copy constructor does not
4345 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004346 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004347 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004348 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004349 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004350 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004351 return handleLValueToRValueConversion(
4352 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4353 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004354 }
4355
4356 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004357 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004358 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004359 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004360
John McCalld7bca762012-05-01 00:38:49 +00004361 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004362 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4363
Richard Smith08d6a2c2013-07-24 07:11:57 +00004364 // A scope for temporaries lifetime-extended by reference members.
4365 BlockScopeRAII LifetimeExtendedScope(Info);
4366
Richard Smith253c2a32012-01-27 01:14:48 +00004367 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004368 unsigned BasesSeen = 0;
4369#ifndef NDEBUG
4370 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4371#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004372 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004373 LValue Subobject = This;
4374 APValue *Value = &Result;
4375
4376 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004377 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004378 if (I->isBaseInitializer()) {
4379 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004380#ifndef NDEBUG
4381 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004382 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004383 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4384 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4385 "base class initializers not in expected order");
4386 ++BaseIt;
4387#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004388 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004389 BaseType->getAsCXXRecordDecl(), &Layout))
4390 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004391 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004392 } else if ((FD = I->getMember())) {
4393 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004394 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004395 if (RD->isUnion()) {
4396 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004397 Value = &Result.getUnionValue();
4398 } else {
4399 Value = &Result.getStructField(FD->getFieldIndex());
4400 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004401 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004402 // Walk the indirect field decl's chain to find the object to initialize,
4403 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004404 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004405 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004406 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4407 // Switch the union field if it differs. This happens if we had
4408 // preceding zero-initialization, and we're now initializing a union
4409 // subobject other than the first.
4410 // FIXME: In this case, the values of the other subobjects are
4411 // specified, since zero-initialization sets all padding bits to zero.
4412 if (Value->isUninit() ||
4413 (Value->isUnion() && Value->getUnionField() != FD)) {
4414 if (CD->isUnion())
4415 *Value = APValue(FD);
4416 else
4417 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004418 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004419 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004420 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004421 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004422 if (CD->isUnion())
4423 Value = &Value->getUnionValue();
4424 else
4425 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004426 }
Richard Smithd62306a2011-11-10 06:34:14 +00004427 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004428 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004429 }
Richard Smith253c2a32012-01-27 01:14:48 +00004430
Richard Smith08d6a2c2013-07-24 07:11:57 +00004431 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004432 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4433 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004434 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004435 // If we're checking for a potential constant expression, evaluate all
4436 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004437 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004438 return false;
4439 Success = false;
4440 }
Richard Smithd62306a2011-11-10 06:34:14 +00004441 }
4442
Richard Smithd9f663b2013-04-22 15:31:51 +00004443 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004444 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004445}
4446
Richard Smith5179eb72016-06-28 19:03:57 +00004447static bool HandleConstructorCall(const Expr *E, const LValue &This,
4448 ArrayRef<const Expr*> Args,
4449 const CXXConstructorDecl *Definition,
4450 EvalInfo &Info, APValue &Result) {
4451 ArgVector ArgValues(Args.size());
4452 if (!EvaluateArgs(Args, ArgValues, Info))
4453 return false;
4454
4455 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4456 Info, Result);
4457}
4458
Eli Friedman9a156e52008-11-12 09:44:48 +00004459//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004460// Generic Evaluation
4461//===----------------------------------------------------------------------===//
4462namespace {
4463
Aaron Ballman68af21c2014-01-03 19:26:43 +00004464template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004465class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004466 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004467private:
Richard Smith52a980a2015-08-28 02:43:42 +00004468 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004469 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004470 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004471 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004472 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004473 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004474 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004475
Richard Smith17100ba2012-02-16 02:46:34 +00004476 // Check whether a conditional operator with a non-constant condition is a
4477 // potential constant expression. If neither arm is a potential constant
4478 // expression, then the conditional operator is not either.
4479 template<typename ConditionalOperator>
4480 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004481 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004482
4483 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004484 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004485 {
Richard Smith17100ba2012-02-16 02:46:34 +00004486 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004487 StmtVisitorTy::Visit(E->getFalseExpr());
4488 if (Diag.empty())
4489 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004490 }
Richard Smith17100ba2012-02-16 02:46:34 +00004491
George Burgess IV8c892b52016-05-25 22:31:54 +00004492 {
4493 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004494 Diag.clear();
4495 StmtVisitorTy::Visit(E->getTrueExpr());
4496 if (Diag.empty())
4497 return;
4498 }
4499
4500 Error(E, diag::note_constexpr_conditional_never_const);
4501 }
4502
4503
4504 template<typename ConditionalOperator>
4505 bool HandleConditionalOperator(const ConditionalOperator *E) {
4506 bool BoolResult;
4507 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004508 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004509 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004510 return false;
4511 }
4512 if (Info.noteFailure()) {
4513 StmtVisitorTy::Visit(E->getTrueExpr());
4514 StmtVisitorTy::Visit(E->getFalseExpr());
4515 }
Richard Smith17100ba2012-02-16 02:46:34 +00004516 return false;
4517 }
4518
4519 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4520 return StmtVisitorTy::Visit(EvalExpr);
4521 }
4522
Peter Collingbournee9200682011-05-13 03:29:01 +00004523protected:
4524 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004525 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004526 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4527
Richard Smith92b1ce02011-12-12 09:28:41 +00004528 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004529 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004530 }
4531
Aaron Ballman68af21c2014-01-03 19:26:43 +00004532 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004533
4534public:
4535 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4536
4537 EvalInfo &getEvalInfo() { return Info; }
4538
Richard Smithf57d8cb2011-12-09 22:58:01 +00004539 /// Report an evaluation error. This should only be called when an error is
4540 /// first discovered. When propagating an error, just return false.
4541 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004542 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004543 return false;
4544 }
4545 bool Error(const Expr *E) {
4546 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4547 }
4548
Aaron Ballman68af21c2014-01-03 19:26:43 +00004549 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004550 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004551 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004552 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004553 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004554 }
4555
Aaron Ballman68af21c2014-01-03 19:26:43 +00004556 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004557 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004558 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004559 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004560 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004561 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004562 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004563 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004564 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004565 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004566 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004567 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004568 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004569 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004570 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004571 // The initializer may not have been parsed yet, or might be erroneous.
4572 if (!E->getExpr())
4573 return Error(E);
4574 return StmtVisitorTy::Visit(E->getExpr());
4575 }
Richard Smith5894a912011-12-19 22:12:41 +00004576 // We cannot create any objects for which cleanups are required, so there is
4577 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004578 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004579 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004580
Aaron Ballman68af21c2014-01-03 19:26:43 +00004581 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004582 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4583 return static_cast<Derived*>(this)->VisitCastExpr(E);
4584 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004585 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004586 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4587 return static_cast<Derived*>(this)->VisitCastExpr(E);
4588 }
4589
Aaron Ballman68af21c2014-01-03 19:26:43 +00004590 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004591 switch (E->getOpcode()) {
4592 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004593 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004594
4595 case BO_Comma:
4596 VisitIgnoredValue(E->getLHS());
4597 return StmtVisitorTy::Visit(E->getRHS());
4598
4599 case BO_PtrMemD:
4600 case BO_PtrMemI: {
4601 LValue Obj;
4602 if (!HandleMemberPointerAccess(Info, E, Obj))
4603 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004604 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004605 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004606 return false;
4607 return DerivedSuccess(Result, E);
4608 }
4609 }
4610 }
4611
Aaron Ballman68af21c2014-01-03 19:26:43 +00004612 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004613 // Evaluate and cache the common expression. We treat it as a temporary,
4614 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004615 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004616 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004617 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004618
Richard Smith17100ba2012-02-16 02:46:34 +00004619 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004620 }
4621
Aaron Ballman68af21c2014-01-03 19:26:43 +00004622 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004623 bool IsBcpCall = false;
4624 // If the condition (ignoring parens) is a __builtin_constant_p call,
4625 // the result is a constant expression if it can be folded without
4626 // side-effects. This is an important GNU extension. See GCC PR38377
4627 // for discussion.
4628 if (const CallExpr *CallCE =
4629 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004630 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004631 IsBcpCall = true;
4632
4633 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4634 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004635 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004636 return false;
4637
Richard Smith6d4c6582013-11-05 22:18:15 +00004638 FoldConstant Fold(Info, IsBcpCall);
4639 if (!HandleConditionalOperator(E)) {
4640 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004641 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004642 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004643
4644 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004645 }
4646
Aaron Ballman68af21c2014-01-03 19:26:43 +00004647 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004648 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4649 return DerivedSuccess(*Value, E);
4650
4651 const Expr *Source = E->getSourceExpr();
4652 if (!Source)
4653 return Error(E);
4654 if (Source == E) { // sanity checking.
4655 assert(0 && "OpaqueValueExpr recursively refers to itself");
4656 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004657 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004658 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004659 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004660
Aaron Ballman68af21c2014-01-03 19:26:43 +00004661 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004662 APValue Result;
4663 if (!handleCallExpr(E, Result, nullptr))
4664 return false;
4665 return DerivedSuccess(Result, E);
4666 }
4667
4668 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004669 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004670 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004671 QualType CalleeType = Callee->getType();
4672
Craig Topper36250ad2014-05-12 05:36:57 +00004673 const FunctionDecl *FD = nullptr;
4674 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004675 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004676 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004677
Richard Smithe97cbd72011-11-11 04:05:33 +00004678 // Extract function decl and 'this' pointer from the callee.
4679 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004680 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004681 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4682 // Explicit bound member calls, such as x.f() or p->g();
4683 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004684 return false;
4685 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004686 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004687 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004688 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4689 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004690 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4691 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004692 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004693 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004694 return Error(Callee);
4695
4696 FD = dyn_cast<FunctionDecl>(Member);
4697 if (!FD)
4698 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004699 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004700 LValue Call;
4701 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004702 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004703
Richard Smitha8105bc2012-01-06 16:39:00 +00004704 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004705 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004706 FD = dyn_cast_or_null<FunctionDecl>(
4707 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004708 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004709 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004710 // Don't call function pointers which have been cast to some other type.
4711 // Per DR (no number yet), the caller and callee can differ in noexcept.
4712 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4713 CalleeType->getPointeeType(), FD->getType())) {
4714 return Error(E);
4715 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004716
4717 // Overloaded operator calls to member functions are represented as normal
4718 // calls with '*this' as the first argument.
4719 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4720 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004721 // FIXME: When selecting an implicit conversion for an overloaded
4722 // operator delete, we sometimes try to evaluate calls to conversion
4723 // operators without a 'this' parameter!
4724 if (Args.empty())
4725 return Error(E);
4726
Nick Lewycky13073a62017-06-12 21:15:44 +00004727 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004728 return false;
4729 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004730 Args = Args.slice(1);
Daniel Jasperffdee092017-05-02 19:21:42 +00004731 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004732 // Map the static invoker for the lambda back to the call operator.
4733 // Conveniently, we don't have to slice out the 'this' argument (as is
4734 // being done for the non-static case), since a static member function
4735 // doesn't have an implicit argument passed in.
4736 const CXXRecordDecl *ClosureClass = MD->getParent();
4737 assert(
4738 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4739 "Number of captures must be zero for conversion to function-ptr");
4740
4741 const CXXMethodDecl *LambdaCallOp =
4742 ClosureClass->getLambdaCallOperator();
4743
4744 // Set 'FD', the function that will be called below, to the call
4745 // operator. If the closure object represents a generic lambda, find
4746 // the corresponding specialization of the call operator.
4747
4748 if (ClosureClass->isGenericLambda()) {
4749 assert(MD->isFunctionTemplateSpecialization() &&
4750 "A generic lambda's static-invoker function must be a "
4751 "template specialization");
4752 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4753 FunctionTemplateDecl *CallOpTemplate =
4754 LambdaCallOp->getDescribedFunctionTemplate();
4755 void *InsertPos = nullptr;
4756 FunctionDecl *CorrespondingCallOpSpecialization =
4757 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4758 assert(CorrespondingCallOpSpecialization &&
4759 "We must always have a function call operator specialization "
4760 "that corresponds to our static invoker specialization");
4761 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4762 } else
4763 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004764 }
4765
Daniel Jasperffdee092017-05-02 19:21:42 +00004766
Richard Smithe97cbd72011-11-11 04:05:33 +00004767 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004768 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004769
Richard Smith47b34932012-02-01 02:39:43 +00004770 if (This && !This->checkSubobject(Info, E, CSK_This))
4771 return false;
4772
Richard Smith3607ffe2012-02-13 03:54:03 +00004773 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4774 // calls to such functions in constant expressions.
4775 if (This && !HasQualifier &&
4776 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4777 return Error(E, diag::note_constexpr_virtual_call);
4778
Craig Topper36250ad2014-05-12 05:36:57 +00004779 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004780 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004781
Nick Lewycky13073a62017-06-12 21:15:44 +00004782 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4783 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004784 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004785 return false;
4786
Richard Smith52a980a2015-08-28 02:43:42 +00004787 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004788 }
4789
Aaron Ballman68af21c2014-01-03 19:26:43 +00004790 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004791 return StmtVisitorTy::Visit(E->getInitializer());
4792 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004793 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004794 if (E->getNumInits() == 0)
4795 return DerivedZeroInitialization(E);
4796 if (E->getNumInits() == 1)
4797 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004798 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004799 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004800 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004801 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004802 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004803 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004804 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004805 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004806 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004807 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004808 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004809
Richard Smithd62306a2011-11-10 06:34:14 +00004810 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004811 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004812 assert(!E->isArrow() && "missing call to bound member function?");
4813
Richard Smith2e312c82012-03-03 22:46:17 +00004814 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004815 if (!Evaluate(Val, Info, E->getBase()))
4816 return false;
4817
4818 QualType BaseTy = E->getBase()->getType();
4819
4820 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004821 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004822 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004823 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004824 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4825
Richard Smith3229b742013-05-05 21:17:10 +00004826 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004827 SubobjectDesignator Designator(BaseTy);
4828 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004829
Richard Smith3229b742013-05-05 21:17:10 +00004830 APValue Result;
4831 return extractSubobject(Info, E, Obj, Designator, Result) &&
4832 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004833 }
4834
Aaron Ballman68af21c2014-01-03 19:26:43 +00004835 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004836 switch (E->getCastKind()) {
4837 default:
4838 break;
4839
Richard Smitha23ab512013-05-23 00:30:41 +00004840 case CK_AtomicToNonAtomic: {
4841 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004842 // This does not need to be done in place even for class/array types:
4843 // atomic-to-non-atomic conversion implies copying the object
4844 // representation.
4845 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004846 return false;
4847 return DerivedSuccess(AtomicVal, E);
4848 }
4849
Richard Smith11562c52011-10-28 17:51:58 +00004850 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004851 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004852 return StmtVisitorTy::Visit(E->getSubExpr());
4853
4854 case CK_LValueToRValue: {
4855 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004856 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4857 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004858 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004859 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004860 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004861 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004862 return false;
4863 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004864 }
4865 }
4866
Richard Smithf57d8cb2011-12-09 22:58:01 +00004867 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004868 }
4869
Aaron Ballman68af21c2014-01-03 19:26:43 +00004870 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004871 return VisitUnaryPostIncDec(UO);
4872 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004873 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004874 return VisitUnaryPostIncDec(UO);
4875 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004876 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004877 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004878 return Error(UO);
4879
4880 LValue LVal;
4881 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4882 return false;
4883 APValue RVal;
4884 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4885 UO->isIncrementOp(), &RVal))
4886 return false;
4887 return DerivedSuccess(RVal, UO);
4888 }
4889
Aaron Ballman68af21c2014-01-03 19:26:43 +00004890 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004891 // We will have checked the full-expressions inside the statement expression
4892 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004893 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004894 return Error(E);
4895
Richard Smith08d6a2c2013-07-24 07:11:57 +00004896 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004897 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004898 if (CS->body_empty())
4899 return true;
4900
Richard Smith51f03172013-06-20 03:00:05 +00004901 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4902 BE = CS->body_end();
4903 /**/; ++BI) {
4904 if (BI + 1 == BE) {
4905 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4906 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004907 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004908 diag::note_constexpr_stmt_expr_unsupported);
4909 return false;
4910 }
4911 return this->Visit(FinalExpr);
4912 }
4913
4914 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004915 StmtResult Result = { ReturnValue, nullptr };
4916 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004917 if (ESR != ESR_Succeeded) {
4918 // FIXME: If the statement-expression terminated due to 'return',
4919 // 'break', or 'continue', it would be nice to propagate that to
4920 // the outer statement evaluation rather than bailing out.
4921 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004922 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004923 diag::note_constexpr_stmt_expr_unsupported);
4924 return false;
4925 }
4926 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004927
4928 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004929 }
4930
Richard Smith4a678122011-10-24 18:44:57 +00004931 /// Visit a value which is evaluated, but whose value is ignored.
4932 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004933 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004934 }
David Majnemere9807b22016-02-26 04:23:19 +00004935
4936 /// Potentially visit a MemberExpr's base expression.
4937 void VisitIgnoredBaseExpression(const Expr *E) {
4938 // While MSVC doesn't evaluate the base expression, it does diagnose the
4939 // presence of side-effecting behavior.
4940 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4941 return;
4942 VisitIgnoredValue(E);
4943 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004944};
4945
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004946}
Peter Collingbournee9200682011-05-13 03:29:01 +00004947
4948//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004949// Common base class for lvalue and temporary evaluation.
4950//===----------------------------------------------------------------------===//
4951namespace {
4952template<class Derived>
4953class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004954 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004955protected:
4956 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00004957 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00004958 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004959 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004960
4961 bool Success(APValue::LValueBase B) {
4962 Result.set(B);
4963 return true;
4964 }
4965
George Burgess IVf9013bf2017-02-10 22:52:29 +00004966 bool evaluatePointer(const Expr *E, LValue &Result) {
4967 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4968 }
4969
Richard Smith027bf112011-11-17 22:56:20 +00004970public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004971 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4972 : ExprEvaluatorBaseTy(Info), Result(Result),
4973 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00004974
Richard Smith2e312c82012-03-03 22:46:17 +00004975 bool Success(const APValue &V, const Expr *E) {
4976 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004977 return true;
4978 }
Richard Smith027bf112011-11-17 22:56:20 +00004979
Richard Smith027bf112011-11-17 22:56:20 +00004980 bool VisitMemberExpr(const MemberExpr *E) {
4981 // Handle non-static data members.
4982 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004983 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004984 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004985 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00004986 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004987 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004988 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004989 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004990 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004991 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004992 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004993 BaseTy = E->getBase()->getType();
4994 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004995 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004996 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004997 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004998 Result.setInvalid(E);
4999 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005000 }
Richard Smith027bf112011-11-17 22:56:20 +00005001
Richard Smith1b78b3d2012-01-25 22:15:11 +00005002 const ValueDecl *MD = E->getMemberDecl();
5003 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5004 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5005 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5006 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005007 if (!HandleLValueMember(this->Info, E, Result, FD))
5008 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005009 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005010 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5011 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005012 } else
5013 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005014
Richard Smith1b78b3d2012-01-25 22:15:11 +00005015 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005016 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005017 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005018 RefValue))
5019 return false;
5020 return Success(RefValue, E);
5021 }
5022 return true;
5023 }
5024
5025 bool VisitBinaryOperator(const BinaryOperator *E) {
5026 switch (E->getOpcode()) {
5027 default:
5028 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5029
5030 case BO_PtrMemD:
5031 case BO_PtrMemI:
5032 return HandleMemberPointerAccess(this->Info, E, Result);
5033 }
5034 }
5035
5036 bool VisitCastExpr(const CastExpr *E) {
5037 switch (E->getCastKind()) {
5038 default:
5039 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5040
5041 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005042 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005043 if (!this->Visit(E->getSubExpr()))
5044 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005045
5046 // Now figure out the necessary offset to add to the base LV to get from
5047 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005048 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5049 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005050 }
5051 }
5052};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005053}
Richard Smith027bf112011-11-17 22:56:20 +00005054
5055//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005056// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005057//
5058// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5059// function designators (in C), decl references to void objects (in C), and
5060// temporaries (if building with -Wno-address-of-temporary).
5061//
5062// LValue evaluation produces values comprising a base expression of one of the
5063// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005064// - Declarations
5065// * VarDecl
5066// * FunctionDecl
5067// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005068// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005069// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005070// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005071// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005072// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005073// * ObjCEncodeExpr
5074// * AddrLabelExpr
5075// * BlockExpr
5076// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005077// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005078// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005079// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005080// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5081// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005082// * A MaterializeTemporaryExpr that has static storage duration, with no
5083// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005084// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005085//===----------------------------------------------------------------------===//
5086namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005087class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005088 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005089public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005090 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5091 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005092
Richard Smith11562c52011-10-28 17:51:58 +00005093 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005094 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005095
Peter Collingbournee9200682011-05-13 03:29:01 +00005096 bool VisitDeclRefExpr(const DeclRefExpr *E);
5097 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005098 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005099 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5100 bool VisitMemberExpr(const MemberExpr *E);
5101 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5102 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005103 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005104 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005105 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5106 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005107 bool VisitUnaryReal(const UnaryOperator *E);
5108 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005109 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5110 return VisitUnaryPreIncDec(UO);
5111 }
5112 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5113 return VisitUnaryPreIncDec(UO);
5114 }
Richard Smith3229b742013-05-05 21:17:10 +00005115 bool VisitBinAssign(const BinaryOperator *BO);
5116 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005117
Peter Collingbournee9200682011-05-13 03:29:01 +00005118 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005119 switch (E->getCastKind()) {
5120 default:
Richard Smith027bf112011-11-17 22:56:20 +00005121 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005122
Eli Friedmance3e02a2011-10-11 00:13:24 +00005123 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005124 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005125 if (!Visit(E->getSubExpr()))
5126 return false;
5127 Result.Designator.setInvalid();
5128 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005129
Richard Smith027bf112011-11-17 22:56:20 +00005130 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005131 if (!Visit(E->getSubExpr()))
5132 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005133 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005134 }
5135 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005136};
5137} // end anonymous namespace
5138
Richard Smith11562c52011-10-28 17:51:58 +00005139/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005140/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005141/// * function designators in C, and
5142/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005143/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005144static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5145 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005146 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005147 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005148 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005149}
5150
Peter Collingbournee9200682011-05-13 03:29:01 +00005151bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005152 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005153 return Success(FD);
5154 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005155 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005156 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005157 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005158 return Error(E);
5159}
Richard Smith733237d2011-10-24 23:14:33 +00005160
Faisal Vali0528a312016-11-13 06:09:16 +00005161
Richard Smith11562c52011-10-28 17:51:58 +00005162bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005163
5164 // If we are within a lambda's call operator, check whether the 'VD' referred
5165 // to within 'E' actually represents a lambda-capture that maps to a
5166 // data-member/field within the closure object, and if so, evaluate to the
5167 // field or what the field refers to.
5168 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5169 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5170 if (Info.checkingPotentialConstantExpression())
5171 return false;
5172 // Start with 'Result' referring to the complete closure object...
5173 Result = *Info.CurrentCall->This;
5174 // ... then update it to refer to the field of the closure object
5175 // that represents the capture.
5176 if (!HandleLValueMember(Info, E, Result, FD))
5177 return false;
5178 // And if the field is of reference type, update 'Result' to refer to what
5179 // the field refers to.
5180 if (FD->getType()->isReferenceType()) {
5181 APValue RVal;
5182 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5183 RVal))
5184 return false;
5185 Result.setFrom(Info.Ctx, RVal);
5186 }
5187 return true;
5188 }
5189 }
Craig Topper36250ad2014-05-12 05:36:57 +00005190 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005191 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5192 // Only if a local variable was declared in the function currently being
5193 // evaluated, do we expect to be able to find its value in the current
5194 // frame. (Otherwise it was likely declared in an enclosing context and
5195 // could either have a valid evaluatable value (for e.g. a constexpr
5196 // variable) or be ill-formed (and trigger an appropriate evaluation
5197 // diagnostic)).
5198 if (Info.CurrentCall->Callee &&
5199 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5200 Frame = Info.CurrentCall;
5201 }
5202 }
Richard Smith3229b742013-05-05 21:17:10 +00005203
Richard Smithfec09922011-11-01 16:57:24 +00005204 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005205 if (Frame) {
5206 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005207 return true;
5208 }
Richard Smithce40ad62011-11-12 22:28:03 +00005209 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005210 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005211
Richard Smith3229b742013-05-05 21:17:10 +00005212 APValue *V;
5213 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005214 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005215 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005216 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005217 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005218 return false;
5219 }
Richard Smith3229b742013-05-05 21:17:10 +00005220 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005221}
5222
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005223bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5224 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005225 // Walk through the expression to find the materialized temporary itself.
5226 SmallVector<const Expr *, 2> CommaLHSs;
5227 SmallVector<SubobjectAdjustment, 2> Adjustments;
5228 const Expr *Inner = E->GetTemporaryExpr()->
5229 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005230
Richard Smith84401042013-06-03 05:03:02 +00005231 // If we passed any comma operators, evaluate their LHSs.
5232 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5233 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5234 return false;
5235
Richard Smithe6c01442013-06-05 00:46:14 +00005236 // A materialized temporary with static storage duration can appear within the
5237 // result of a constant expression evaluation, so we need to preserve its
5238 // value for use outside this evaluation.
5239 APValue *Value;
5240 if (E->getStorageDuration() == SD_Static) {
5241 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005242 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005243 Result.set(E);
5244 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005245 Value = &Info.CurrentCall->
5246 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005247 Result.set(E, Info.CurrentCall->Index);
5248 }
5249
Richard Smithea4ad5d2013-06-06 08:19:16 +00005250 QualType Type = Inner->getType();
5251
Richard Smith84401042013-06-03 05:03:02 +00005252 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005253 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5254 (E->getStorageDuration() == SD_Static &&
5255 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5256 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005257 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005258 }
Richard Smith84401042013-06-03 05:03:02 +00005259
5260 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005261 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5262 --I;
5263 switch (Adjustments[I].Kind) {
5264 case SubobjectAdjustment::DerivedToBaseAdjustment:
5265 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5266 Type, Result))
5267 return false;
5268 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5269 break;
5270
5271 case SubobjectAdjustment::FieldAdjustment:
5272 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5273 return false;
5274 Type = Adjustments[I].Field->getType();
5275 break;
5276
5277 case SubobjectAdjustment::MemberPointerAdjustment:
5278 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5279 Adjustments[I].Ptr.RHS))
5280 return false;
5281 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5282 break;
5283 }
5284 }
5285
5286 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005287}
5288
Peter Collingbournee9200682011-05-13 03:29:01 +00005289bool
5290LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005291 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5292 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005293 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5294 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005295 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005296}
5297
Richard Smith6e525142011-12-27 12:18:28 +00005298bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005299 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005300 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005301
Faisal Valie690b7a2016-07-02 22:34:24 +00005302 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005303 << E->getExprOperand()->getType()
5304 << E->getExprOperand()->getSourceRange();
5305 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005306}
5307
Francois Pichet0066db92012-04-16 04:08:35 +00005308bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5309 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005310}
Francois Pichet0066db92012-04-16 04:08:35 +00005311
Peter Collingbournee9200682011-05-13 03:29:01 +00005312bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005313 // Handle static data members.
5314 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005315 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005316 return VisitVarDecl(E, VD);
5317 }
5318
Richard Smith254a73d2011-10-28 22:34:42 +00005319 // Handle static member functions.
5320 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5321 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005322 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005323 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005324 }
5325 }
5326
Richard Smithd62306a2011-11-10 06:34:14 +00005327 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005328 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005329}
5330
Peter Collingbournee9200682011-05-13 03:29:01 +00005331bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005332 // FIXME: Deal with vectors as array subscript bases.
5333 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005334 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005335
Nick Lewyckyad888682017-04-27 07:27:36 +00005336 bool Success = true;
5337 if (!evaluatePointer(E->getBase(), Result)) {
5338 if (!Info.noteFailure())
5339 return false;
5340 Success = false;
5341 }
Mike Stump11289f42009-09-09 15:08:12 +00005342
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005343 APSInt Index;
5344 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005345 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005346
Nick Lewyckyad888682017-04-27 07:27:36 +00005347 return Success &&
5348 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005349}
Eli Friedman9a156e52008-11-12 09:44:48 +00005350
Peter Collingbournee9200682011-05-13 03:29:01 +00005351bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005352 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005353}
5354
Richard Smith66c96992012-02-18 22:04:06 +00005355bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5356 if (!Visit(E->getSubExpr()))
5357 return false;
5358 // __real is a no-op on scalar lvalues.
5359 if (E->getSubExpr()->getType()->isAnyComplexType())
5360 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5361 return true;
5362}
5363
5364bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5365 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5366 "lvalue __imag__ on scalar?");
5367 if (!Visit(E->getSubExpr()))
5368 return false;
5369 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5370 return true;
5371}
5372
Richard Smith243ef902013-05-05 23:31:59 +00005373bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005374 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005375 return Error(UO);
5376
5377 if (!this->Visit(UO->getSubExpr()))
5378 return false;
5379
Richard Smith243ef902013-05-05 23:31:59 +00005380 return handleIncDec(
5381 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005382 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005383}
5384
5385bool LValueExprEvaluator::VisitCompoundAssignOperator(
5386 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005387 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005388 return Error(CAO);
5389
Richard Smith3229b742013-05-05 21:17:10 +00005390 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005391
5392 // The overall lvalue result is the result of evaluating the LHS.
5393 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005394 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005395 Evaluate(RHS, this->Info, CAO->getRHS());
5396 return false;
5397 }
5398
Richard Smith3229b742013-05-05 21:17:10 +00005399 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5400 return false;
5401
Richard Smith43e77732013-05-07 04:50:00 +00005402 return handleCompoundAssignment(
5403 this->Info, CAO,
5404 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5405 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005406}
5407
5408bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005409 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005410 return Error(E);
5411
Richard Smith3229b742013-05-05 21:17:10 +00005412 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005413
5414 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005415 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005416 Evaluate(NewVal, this->Info, E->getRHS());
5417 return false;
5418 }
5419
Richard Smith3229b742013-05-05 21:17:10 +00005420 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5421 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005422
5423 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005424 NewVal);
5425}
5426
Eli Friedman9a156e52008-11-12 09:44:48 +00005427//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005428// Pointer Evaluation
5429//===----------------------------------------------------------------------===//
5430
George Burgess IVe3763372016-12-22 02:50:20 +00005431/// \brief Attempts to compute the number of bytes available at the pointer
5432/// returned by a function with the alloc_size attribute. Returns true if we
5433/// were successful. Places an unsigned number into `Result`.
5434///
5435/// This expects the given CallExpr to be a call to a function with an
5436/// alloc_size attribute.
5437static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5438 const CallExpr *Call,
5439 llvm::APInt &Result) {
5440 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5441
5442 // alloc_size args are 1-indexed, 0 means not present.
5443 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5444 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5445 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5446 if (Call->getNumArgs() <= SizeArgNo)
5447 return false;
5448
5449 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5450 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5451 return false;
5452 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5453 return false;
5454 Into = Into.zextOrSelf(BitsInSizeT);
5455 return true;
5456 };
5457
5458 APSInt SizeOfElem;
5459 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5460 return false;
5461
5462 if (!AllocSize->getNumElemsParam()) {
5463 Result = std::move(SizeOfElem);
5464 return true;
5465 }
5466
5467 APSInt NumberOfElems;
5468 // Argument numbers start at 1
5469 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5470 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5471 return false;
5472
5473 bool Overflow;
5474 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5475 if (Overflow)
5476 return false;
5477
5478 Result = std::move(BytesAvailable);
5479 return true;
5480}
5481
5482/// \brief Convenience function. LVal's base must be a call to an alloc_size
5483/// function.
5484static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5485 const LValue &LVal,
5486 llvm::APInt &Result) {
5487 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5488 "Can't get the size of a non alloc_size function");
5489 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5490 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5491 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5492}
5493
5494/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5495/// a function with the alloc_size attribute. If it was possible to do so, this
5496/// function will return true, make Result's Base point to said function call,
5497/// and mark Result's Base as invalid.
5498static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5499 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005500 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005501 return false;
5502
5503 // Because we do no form of static analysis, we only support const variables.
5504 //
5505 // Additionally, we can't support parameters, nor can we support static
5506 // variables (in the latter case, use-before-assign isn't UB; in the former,
5507 // we have no clue what they'll be assigned to).
5508 const auto *VD =
5509 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5510 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5511 return false;
5512
5513 const Expr *Init = VD->getAnyInitializer();
5514 if (!Init)
5515 return false;
5516
5517 const Expr *E = Init->IgnoreParens();
5518 if (!tryUnwrapAllocSizeCall(E))
5519 return false;
5520
5521 // Store E instead of E unwrapped so that the type of the LValue's base is
5522 // what the user wanted.
5523 Result.setInvalid(E);
5524
5525 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005526 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005527 return true;
5528}
5529
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005530namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005531class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005532 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005533 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005534 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005535
Peter Collingbournee9200682011-05-13 03:29:01 +00005536 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005537 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005538 return true;
5539 }
George Burgess IVe3763372016-12-22 02:50:20 +00005540
George Burgess IVf9013bf2017-02-10 22:52:29 +00005541 bool evaluateLValue(const Expr *E, LValue &Result) {
5542 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5543 }
5544
5545 bool evaluatePointer(const Expr *E, LValue &Result) {
5546 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5547 }
5548
George Burgess IVe3763372016-12-22 02:50:20 +00005549 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005550public:
Mike Stump11289f42009-09-09 15:08:12 +00005551
George Burgess IVf9013bf2017-02-10 22:52:29 +00005552 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5553 : ExprEvaluatorBaseTy(info), Result(Result),
5554 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005555
Richard Smith2e312c82012-03-03 22:46:17 +00005556 bool Success(const APValue &V, const Expr *E) {
5557 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005558 return true;
5559 }
Richard Smithfddd3842011-12-30 21:15:51 +00005560 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005561 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5562 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005563 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005564 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005565
John McCall45d55e42010-05-07 21:00:08 +00005566 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005567 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005568 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005569 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005570 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005571 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5572 if (Info.noteFailure())
5573 EvaluateIgnoredValue(Info, E->getSubExpr());
5574 return Error(E);
5575 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005576 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005577 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005578 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005579 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005580 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005581 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005582 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005583 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005584 }
Richard Smithd62306a2011-11-10 06:34:14 +00005585 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005586 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005587 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005588 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005589 if (!Info.CurrentCall->This) {
5590 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005591 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005592 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005593 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005594 return false;
5595 }
Richard Smithd62306a2011-11-10 06:34:14 +00005596 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005597 // If we are inside a lambda's call operator, the 'this' expression refers
5598 // to the enclosing '*this' object (either by value or reference) which is
5599 // either copied into the closure object's field that represents the '*this'
5600 // or refers to '*this'.
5601 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5602 // Update 'Result' to refer to the data member/field of the closure object
5603 // that represents the '*this' capture.
5604 if (!HandleLValueMember(Info, E, Result,
Daniel Jasperffdee092017-05-02 19:21:42 +00005605 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005606 return false;
5607 // If we captured '*this' by reference, replace the field with its referent.
5608 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5609 ->isPointerType()) {
5610 APValue RVal;
5611 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5612 RVal))
5613 return false;
5614
5615 Result.setFrom(Info.Ctx, RVal);
5616 }
5617 }
Richard Smithd62306a2011-11-10 06:34:14 +00005618 return true;
5619 }
John McCallc07a0c72011-02-17 10:25:35 +00005620
Eli Friedman449fe542009-03-23 04:56:01 +00005621 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005622};
Chris Lattner05706e882008-07-11 18:11:29 +00005623} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005624
George Burgess IVf9013bf2017-02-10 22:52:29 +00005625static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5626 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005627 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005628 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005629}
5630
John McCall45d55e42010-05-07 21:00:08 +00005631bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005632 if (E->getOpcode() != BO_Add &&
5633 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005634 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005635
Chris Lattner05706e882008-07-11 18:11:29 +00005636 const Expr *PExp = E->getLHS();
5637 const Expr *IExp = E->getRHS();
5638 if (IExp->getType()->isPointerType())
5639 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005640
George Burgess IVf9013bf2017-02-10 22:52:29 +00005641 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005642 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005643 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005644
John McCall45d55e42010-05-07 21:00:08 +00005645 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005646 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005647 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005648
Richard Smith96e0c102011-11-04 02:25:55 +00005649 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005650 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005651
Ted Kremenek28831752012-08-23 20:46:57 +00005652 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005653 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005654}
Eli Friedman9a156e52008-11-12 09:44:48 +00005655
John McCall45d55e42010-05-07 21:00:08 +00005656bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005657 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005658}
Mike Stump11289f42009-09-09 15:08:12 +00005659
Peter Collingbournee9200682011-05-13 03:29:01 +00005660bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5661 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005662
Eli Friedman847a2bc2009-12-27 05:43:15 +00005663 switch (E->getCastKind()) {
5664 default:
5665 break;
5666
John McCalle3027922010-08-25 11:45:40 +00005667 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005668 case CK_CPointerToObjCPointerCast:
5669 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005670 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005671 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005672 if (!Visit(SubExpr))
5673 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005674 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5675 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5676 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005677 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005678 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005679 if (SubExpr->getType()->isVoidPointerType())
5680 CCEDiag(E, diag::note_constexpr_invalid_cast)
5681 << 3 << SubExpr->getType();
5682 else
5683 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5684 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005685 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5686 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005687 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005688
Anders Carlsson18275092010-10-31 20:41:46 +00005689 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005690 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005691 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005692 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005693 if (!Result.Base && Result.Offset.isZero())
5694 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005695
Richard Smithd62306a2011-11-10 06:34:14 +00005696 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005697 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005698 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5699 castAs<PointerType>()->getPointeeType(),
5700 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005701
Richard Smith027bf112011-11-17 22:56:20 +00005702 case CK_BaseToDerived:
5703 if (!Visit(E->getSubExpr()))
5704 return false;
5705 if (!Result.Base && Result.Offset.isZero())
5706 return true;
5707 return HandleBaseToDerivedCast(Info, E, Result);
5708
Richard Smith0b0a0b62011-10-29 20:57:55 +00005709 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005710 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005711 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005712
John McCalle3027922010-08-25 11:45:40 +00005713 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005714 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5715
Richard Smith2e312c82012-03-03 22:46:17 +00005716 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005717 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005718 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005719
John McCall45d55e42010-05-07 21:00:08 +00005720 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005721 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5722 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005723 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005724 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005725 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005726 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005727 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005728 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005729 return true;
5730 } else {
5731 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005732 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005733 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005734 }
5735 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005736
5737 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005738 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005739 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005740 return false;
5741 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005742 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005743 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005744 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005745 return false;
5746 }
Richard Smith96e0c102011-11-04 02:25:55 +00005747 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005748 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5749 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005750 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005751 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005752 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005753 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005754 }
Richard Smithdd785442011-10-31 20:57:44 +00005755
John McCalle3027922010-08-25 11:45:40 +00005756 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005757 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005758
5759 case CK_LValueToRValue: {
5760 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005761 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005762 return false;
5763
5764 APValue RVal;
5765 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5766 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5767 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005768 return InvalidBaseOK &&
5769 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005770 return Success(RVal, E);
5771 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005772 }
5773
Richard Smith11562c52011-10-28 17:51:58 +00005774 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005775}
Chris Lattner05706e882008-07-11 18:11:29 +00005776
Hal Finkel0dd05d42014-10-03 17:18:37 +00005777static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5778 // C++ [expr.alignof]p3:
5779 // When alignof is applied to a reference type, the result is the
5780 // alignment of the referenced type.
5781 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5782 T = Ref->getPointeeType();
5783
5784 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005785 if (T.getQualifiers().hasUnaligned())
5786 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005787 return Info.Ctx.toCharUnitsFromBits(
5788 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5789}
5790
5791static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5792 E = E->IgnoreParens();
5793
5794 // The kinds of expressions that we have special-case logic here for
5795 // should be kept up to date with the special checks for those
5796 // expressions in Sema.
5797
5798 // alignof decl is always accepted, even if it doesn't make sense: we default
5799 // to 1 in those cases.
5800 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5801 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5802 /*RefAsPointee*/true);
5803
5804 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5805 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5806 /*RefAsPointee*/true);
5807
5808 return GetAlignOfType(Info, E->getType());
5809}
5810
George Burgess IVe3763372016-12-22 02:50:20 +00005811// To be clear: this happily visits unsupported builtins. Better name welcomed.
5812bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5813 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5814 return true;
5815
George Burgess IVf9013bf2017-02-10 22:52:29 +00005816 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005817 return false;
5818
5819 Result.setInvalid(E);
5820 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005821 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00005822 return true;
5823}
5824
Peter Collingbournee9200682011-05-13 03:29:01 +00005825bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005826 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005827 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005828
Richard Smith6328cbd2016-11-16 00:57:23 +00005829 if (unsigned BuiltinOp = E->getBuiltinCallee())
5830 return VisitBuiltinCallExpr(E, BuiltinOp);
5831
George Burgess IVe3763372016-12-22 02:50:20 +00005832 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005833}
5834
5835bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5836 unsigned BuiltinOp) {
5837 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005838 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005839 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005840 case Builtin::BI__builtin_assume_aligned: {
5841 // We need to be very careful here because: if the pointer does not have the
5842 // asserted alignment, then the behavior is undefined, and undefined
5843 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005844 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005845 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005846
Hal Finkel0dd05d42014-10-03 17:18:37 +00005847 LValue OffsetResult(Result);
5848 APSInt Alignment;
5849 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5850 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005851 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005852
5853 if (E->getNumArgs() > 2) {
5854 APSInt Offset;
5855 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5856 return false;
5857
Richard Smith642a2362017-01-30 23:30:26 +00005858 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005859 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5860 }
5861
5862 // If there is a base object, then it must have the correct alignment.
5863 if (OffsetResult.Base) {
5864 CharUnits BaseAlignment;
5865 if (const ValueDecl *VD =
5866 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5867 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5868 } else {
5869 BaseAlignment =
5870 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5871 }
5872
5873 if (BaseAlignment < Align) {
5874 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005875 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005876 CCEDiag(E->getArg(0),
5877 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005878 << (unsigned)BaseAlignment.getQuantity()
5879 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005880 return false;
5881 }
5882 }
5883
5884 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005885 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005886 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005887
Richard Smith642a2362017-01-30 23:30:26 +00005888 (OffsetResult.Base
5889 ? CCEDiag(E->getArg(0),
5890 diag::note_constexpr_baa_insufficient_alignment) << 1
5891 : CCEDiag(E->getArg(0),
5892 diag::note_constexpr_baa_value_insufficient_alignment))
5893 << (int)OffsetResult.Offset.getQuantity()
5894 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005895 return false;
5896 }
5897
5898 return true;
5899 }
Richard Smithe9507952016-11-12 01:39:56 +00005900
5901 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005902 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005903 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005904 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005905 if (Info.getLangOpts().CPlusPlus11)
5906 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5907 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005908 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005909 else
5910 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005911 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00005912 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005913 case Builtin::BI__builtin_wcschr:
5914 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005915 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005916 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005917 if (!Visit(E->getArg(0)))
5918 return false;
5919 APSInt Desired;
5920 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5921 return false;
5922 uint64_t MaxLength = uint64_t(-1);
5923 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005924 BuiltinOp != Builtin::BIwcschr &&
5925 BuiltinOp != Builtin::BI__builtin_strchr &&
5926 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005927 APSInt N;
5928 if (!EvaluateInteger(E->getArg(2), N, Info))
5929 return false;
5930 MaxLength = N.getExtValue();
5931 }
5932
Richard Smith8110c9d2016-11-29 19:45:17 +00005933 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005934
Richard Smith8110c9d2016-11-29 19:45:17 +00005935 // Figure out what value we're actually looking for (after converting to
5936 // the corresponding unsigned type if necessary).
5937 uint64_t DesiredVal;
5938 bool StopAtNull = false;
5939 switch (BuiltinOp) {
5940 case Builtin::BIstrchr:
5941 case Builtin::BI__builtin_strchr:
5942 // strchr compares directly to the passed integer, and therefore
5943 // always fails if given an int that is not a char.
5944 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5945 E->getArg(1)->getType(),
5946 Desired),
5947 Desired))
5948 return ZeroInitialization(E);
5949 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005950 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00005951 case Builtin::BImemchr:
5952 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005953 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005954 // memchr compares by converting both sides to unsigned char. That's also
5955 // correct for strchr if we get this far (to cope with plain char being
5956 // unsigned in the strchr case).
5957 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5958 break;
Richard Smithe9507952016-11-12 01:39:56 +00005959
Richard Smith8110c9d2016-11-29 19:45:17 +00005960 case Builtin::BIwcschr:
5961 case Builtin::BI__builtin_wcschr:
5962 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005963 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00005964 case Builtin::BIwmemchr:
5965 case Builtin::BI__builtin_wmemchr:
5966 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5967 DesiredVal = Desired.getZExtValue();
5968 break;
5969 }
Richard Smithe9507952016-11-12 01:39:56 +00005970
5971 for (; MaxLength; --MaxLength) {
5972 APValue Char;
5973 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5974 !Char.isInt())
5975 return false;
5976 if (Char.getInt().getZExtValue() == DesiredVal)
5977 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005978 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005979 break;
5980 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5981 return false;
5982 }
5983 // Not found: return nullptr.
5984 return ZeroInitialization(E);
5985 }
5986
Richard Smith6cbd65d2013-07-11 02:27:57 +00005987 default:
George Burgess IVe3763372016-12-22 02:50:20 +00005988 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005989 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005990}
Chris Lattner05706e882008-07-11 18:11:29 +00005991
5992//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005993// Member Pointer Evaluation
5994//===----------------------------------------------------------------------===//
5995
5996namespace {
5997class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005998 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005999 MemberPtr &Result;
6000
6001 bool Success(const ValueDecl *D) {
6002 Result = MemberPtr(D);
6003 return true;
6004 }
6005public:
6006
6007 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6008 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6009
Richard Smith2e312c82012-03-03 22:46:17 +00006010 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006011 Result.setFrom(V);
6012 return true;
6013 }
Richard Smithfddd3842011-12-30 21:15:51 +00006014 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006015 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006016 }
6017
6018 bool VisitCastExpr(const CastExpr *E);
6019 bool VisitUnaryAddrOf(const UnaryOperator *E);
6020};
6021} // end anonymous namespace
6022
6023static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6024 EvalInfo &Info) {
6025 assert(E->isRValue() && E->getType()->isMemberPointerType());
6026 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6027}
6028
6029bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6030 switch (E->getCastKind()) {
6031 default:
6032 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6033
6034 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006035 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006036 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006037
6038 case CK_BaseToDerivedMemberPointer: {
6039 if (!Visit(E->getSubExpr()))
6040 return false;
6041 if (E->path_empty())
6042 return true;
6043 // Base-to-derived member pointer casts store the path in derived-to-base
6044 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6045 // the wrong end of the derived->base arc, so stagger the path by one class.
6046 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6047 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6048 PathI != PathE; ++PathI) {
6049 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6050 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6051 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006052 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006053 }
6054 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6055 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006056 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006057 return true;
6058 }
6059
6060 case CK_DerivedToBaseMemberPointer:
6061 if (!Visit(E->getSubExpr()))
6062 return false;
6063 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6064 PathE = E->path_end(); PathI != PathE; ++PathI) {
6065 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6066 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6067 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006068 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006069 }
6070 return true;
6071 }
6072}
6073
6074bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6075 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6076 // member can be formed.
6077 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6078}
6079
6080//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006081// Record Evaluation
6082//===----------------------------------------------------------------------===//
6083
6084namespace {
6085 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006086 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006087 const LValue &This;
6088 APValue &Result;
6089 public:
6090
6091 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6092 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6093
Richard Smith2e312c82012-03-03 22:46:17 +00006094 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006095 Result = V;
6096 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006097 }
Richard Smithb8348f52016-05-12 22:16:28 +00006098 bool ZeroInitialization(const Expr *E) {
6099 return ZeroInitialization(E, E->getType());
6100 }
6101 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006102
Richard Smith52a980a2015-08-28 02:43:42 +00006103 bool VisitCallExpr(const CallExpr *E) {
6104 return handleCallExpr(E, Result, &This);
6105 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006106 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006107 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006108 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6109 return VisitCXXConstructExpr(E, E->getType());
6110 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006111 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006112 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006113 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006114 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006115 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006116}
Richard Smithd62306a2011-11-10 06:34:14 +00006117
Richard Smithfddd3842011-12-30 21:15:51 +00006118/// Perform zero-initialization on an object of non-union class type.
6119/// C++11 [dcl.init]p5:
6120/// To zero-initialize an object or reference of type T means:
6121/// [...]
6122/// -- if T is a (possibly cv-qualified) non-union class type,
6123/// each non-static data member and each base-class subobject is
6124/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006125static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6126 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006127 const LValue &This, APValue &Result) {
6128 assert(!RD->isUnion() && "Expected non-union class type");
6129 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6130 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006131 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006132
John McCalld7bca762012-05-01 00:38:49 +00006133 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006134 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6135
6136 if (CD) {
6137 unsigned Index = 0;
6138 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006139 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006140 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6141 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006142 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6143 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006144 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006145 Result.getStructBase(Index)))
6146 return false;
6147 }
6148 }
6149
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006150 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006151 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006152 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006153 continue;
6154
6155 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006156 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006157 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006158
David Blaikie2d7c57e2012-04-30 02:36:29 +00006159 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006160 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006161 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006162 return false;
6163 }
6164
6165 return true;
6166}
6167
Richard Smithb8348f52016-05-12 22:16:28 +00006168bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6169 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006170 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006171 if (RD->isUnion()) {
6172 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6173 // object's first non-static named data member is zero-initialized
6174 RecordDecl::field_iterator I = RD->field_begin();
6175 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006176 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006177 return true;
6178 }
6179
6180 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006181 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006182 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006183 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006184 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006185 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006186 }
6187
Richard Smith5d108602012-02-17 00:44:16 +00006188 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006189 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006190 return false;
6191 }
6192
Richard Smitha8105bc2012-01-06 16:39:00 +00006193 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006194}
6195
Richard Smithe97cbd72011-11-11 04:05:33 +00006196bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6197 switch (E->getCastKind()) {
6198 default:
6199 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6200
6201 case CK_ConstructorConversion:
6202 return Visit(E->getSubExpr());
6203
6204 case CK_DerivedToBase:
6205 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006206 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006207 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006208 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006209 if (!DerivedObject.isStruct())
6210 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006211
6212 // Derived-to-base rvalue conversion: just slice off the derived part.
6213 APValue *Value = &DerivedObject;
6214 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6215 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6216 PathE = E->path_end(); PathI != PathE; ++PathI) {
6217 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6218 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6219 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6220 RD = Base;
6221 }
6222 Result = *Value;
6223 return true;
6224 }
6225 }
6226}
6227
Richard Smithd62306a2011-11-10 06:34:14 +00006228bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006229 if (E->isTransparent())
6230 return Visit(E->getInit(0));
6231
Richard Smithd62306a2011-11-10 06:34:14 +00006232 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006233 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006234 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6235
6236 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006237 const FieldDecl *Field = E->getInitializedFieldInUnion();
6238 Result = APValue(Field);
6239 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006240 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006241
6242 // If the initializer list for a union does not contain any elements, the
6243 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006244 // FIXME: The element should be initialized from an initializer list.
6245 // Is this difference ever observable for initializer lists which
6246 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006247 ImplicitValueInitExpr VIE(Field->getType());
6248 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6249
Richard Smithd62306a2011-11-10 06:34:14 +00006250 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006251 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6252 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006253
6254 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6255 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6256 isa<CXXDefaultInitExpr>(InitExpr));
6257
Richard Smithb228a862012-02-15 02:18:13 +00006258 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006259 }
6260
Richard Smith872307e2016-03-08 22:17:41 +00006261 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006262 if (Result.isUninit())
6263 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6264 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006265 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006266 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006267
6268 // Initialize base classes.
6269 if (CXXRD) {
6270 for (const auto &Base : CXXRD->bases()) {
6271 assert(ElementNo < E->getNumInits() && "missing init for base class");
6272 const Expr *Init = E->getInit(ElementNo);
6273
6274 LValue Subobject = This;
6275 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6276 return false;
6277
6278 APValue &FieldVal = Result.getStructBase(ElementNo);
6279 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006280 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006281 return false;
6282 Success = false;
6283 }
6284 ++ElementNo;
6285 }
6286 }
6287
6288 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006289 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006290 // Anonymous bit-fields are not considered members of the class for
6291 // purposes of aggregate initialization.
6292 if (Field->isUnnamedBitfield())
6293 continue;
6294
6295 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006296
Richard Smith253c2a32012-01-27 01:14:48 +00006297 bool HaveInit = ElementNo < E->getNumInits();
6298
6299 // FIXME: Diagnostics here should point to the end of the initializer
6300 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006301 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006302 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006303 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006304
6305 // Perform an implicit value-initialization for members beyond the end of
6306 // the initializer list.
6307 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006308 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006309
Richard Smith852c9db2013-04-20 22:23:05 +00006310 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6311 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6312 isa<CXXDefaultInitExpr>(Init));
6313
Richard Smith49ca8aa2013-08-06 07:09:20 +00006314 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6315 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6316 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006317 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006318 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006319 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006320 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006321 }
6322 }
6323
Richard Smith253c2a32012-01-27 01:14:48 +00006324 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006325}
6326
Richard Smithb8348f52016-05-12 22:16:28 +00006327bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6328 QualType T) {
6329 // Note that E's type is not necessarily the type of our class here; we might
6330 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006331 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006332 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6333
Richard Smithfddd3842011-12-30 21:15:51 +00006334 bool ZeroInit = E->requiresZeroInitialization();
6335 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006336 // If we've already performed zero-initialization, we're already done.
6337 if (!Result.isUninit())
6338 return true;
6339
Richard Smithda3f4fd2014-03-05 23:32:50 +00006340 // We can get here in two different ways:
6341 // 1) We're performing value-initialization, and should zero-initialize
6342 // the object, or
6343 // 2) We're performing default-initialization of an object with a trivial
6344 // constexpr default constructor, in which case we should start the
6345 // lifetimes of all the base subobjects (there can be no data member
6346 // subobjects in this case) per [basic.life]p1.
6347 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006348 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006349 }
6350
Craig Topper36250ad2014-05-12 05:36:57 +00006351 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006352 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006353
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006354 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006355 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006356
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006357 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006358 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006359 if (const MaterializeTemporaryExpr *ME
6360 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6361 return Visit(ME->GetTemporaryExpr());
6362
Richard Smithb8348f52016-05-12 22:16:28 +00006363 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006364 return false;
6365
Craig Topper5fc8fc22014-08-27 06:28:36 +00006366 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006367 return HandleConstructorCall(E, This, Args,
6368 cast<CXXConstructorDecl>(Definition), Info,
6369 Result);
6370}
6371
6372bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6373 const CXXInheritedCtorInitExpr *E) {
6374 if (!Info.CurrentCall) {
6375 assert(Info.checkingPotentialConstantExpression());
6376 return false;
6377 }
6378
6379 const CXXConstructorDecl *FD = E->getConstructor();
6380 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6381 return false;
6382
6383 const FunctionDecl *Definition = nullptr;
6384 auto Body = FD->getBody(Definition);
6385
6386 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6387 return false;
6388
6389 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006390 cast<CXXConstructorDecl>(Definition), Info,
6391 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006392}
6393
Richard Smithcc1b96d2013-06-12 22:31:48 +00006394bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6395 const CXXStdInitializerListExpr *E) {
6396 const ConstantArrayType *ArrayType =
6397 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6398
6399 LValue Array;
6400 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6401 return false;
6402
6403 // Get a pointer to the first element of the array.
6404 Array.addArray(Info, E, ArrayType);
6405
6406 // FIXME: Perform the checks on the field types in SemaInit.
6407 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6408 RecordDecl::field_iterator Field = Record->field_begin();
6409 if (Field == Record->field_end())
6410 return Error(E);
6411
6412 // Start pointer.
6413 if (!Field->getType()->isPointerType() ||
6414 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6415 ArrayType->getElementType()))
6416 return Error(E);
6417
6418 // FIXME: What if the initializer_list type has base classes, etc?
6419 Result = APValue(APValue::UninitStruct(), 0, 2);
6420 Array.moveInto(Result.getStructField(0));
6421
6422 if (++Field == Record->field_end())
6423 return Error(E);
6424
6425 if (Field->getType()->isPointerType() &&
6426 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6427 ArrayType->getElementType())) {
6428 // End pointer.
6429 if (!HandleLValueArrayAdjustment(Info, E, Array,
6430 ArrayType->getElementType(),
6431 ArrayType->getSize().getZExtValue()))
6432 return false;
6433 Array.moveInto(Result.getStructField(1));
6434 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6435 // Length.
6436 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6437 else
6438 return Error(E);
6439
6440 if (++Field != Record->field_end())
6441 return Error(E);
6442
6443 return true;
6444}
6445
Faisal Valic72a08c2017-01-09 03:02:53 +00006446bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6447 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6448 if (ClosureClass->isInvalidDecl()) return false;
6449
6450 if (Info.checkingPotentialConstantExpression()) return true;
Daniel Jasperffdee092017-05-02 19:21:42 +00006451
Faisal Vali051e3a22017-02-16 04:12:21 +00006452 const size_t NumFields =
6453 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006454
6455 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6456 E->capture_init_end()) &&
6457 "The number of lambda capture initializers should equal the number of "
6458 "fields within the closure type");
6459
Faisal Vali051e3a22017-02-16 04:12:21 +00006460 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6461 // Iterate through all the lambda's closure object's fields and initialize
6462 // them.
6463 auto *CaptureInitIt = E->capture_init_begin();
6464 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6465 bool Success = true;
6466 for (const auto *Field : ClosureClass->fields()) {
6467 assert(CaptureInitIt != E->capture_init_end());
6468 // Get the initializer for this field
6469 Expr *const CurFieldInit = *CaptureInitIt++;
Daniel Jasperffdee092017-05-02 19:21:42 +00006470
Faisal Vali051e3a22017-02-16 04:12:21 +00006471 // If there is no initializer, either this is a VLA or an error has
6472 // occurred.
6473 if (!CurFieldInit)
6474 return Error(E);
6475
6476 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6477 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6478 if (!Info.keepEvaluatingAfterFailure())
6479 return false;
6480 Success = false;
6481 }
6482 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006483 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006484 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006485}
6486
Richard Smithd62306a2011-11-10 06:34:14 +00006487static bool EvaluateRecord(const Expr *E, const LValue &This,
6488 APValue &Result, EvalInfo &Info) {
6489 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006490 "can't evaluate expression as a record rvalue");
6491 return RecordExprEvaluator(Info, This, Result).Visit(E);
6492}
6493
6494//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006495// Temporary Evaluation
6496//
6497// Temporaries are represented in the AST as rvalues, but generally behave like
6498// lvalues. The full-object of which the temporary is a subobject is implicitly
6499// materialized so that a reference can bind to it.
6500//===----------------------------------------------------------------------===//
6501namespace {
6502class TemporaryExprEvaluator
6503 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6504public:
6505 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006506 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006507
6508 /// Visit an expression which constructs the value of this temporary.
6509 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006510 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006511 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6512 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006513 }
6514
6515 bool VisitCastExpr(const CastExpr *E) {
6516 switch (E->getCastKind()) {
6517 default:
6518 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6519
6520 case CK_ConstructorConversion:
6521 return VisitConstructExpr(E->getSubExpr());
6522 }
6523 }
6524 bool VisitInitListExpr(const InitListExpr *E) {
6525 return VisitConstructExpr(E);
6526 }
6527 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6528 return VisitConstructExpr(E);
6529 }
6530 bool VisitCallExpr(const CallExpr *E) {
6531 return VisitConstructExpr(E);
6532 }
Richard Smith513955c2014-12-17 19:24:30 +00006533 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6534 return VisitConstructExpr(E);
6535 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006536 bool VisitLambdaExpr(const LambdaExpr *E) {
6537 return VisitConstructExpr(E);
6538 }
Richard Smith027bf112011-11-17 22:56:20 +00006539};
6540} // end anonymous namespace
6541
6542/// Evaluate an expression of record type as a temporary.
6543static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006544 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006545 return TemporaryExprEvaluator(Info, Result).Visit(E);
6546}
6547
6548//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006549// Vector Evaluation
6550//===----------------------------------------------------------------------===//
6551
6552namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006553 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006554 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006555 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006556 public:
Mike Stump11289f42009-09-09 15:08:12 +00006557
Richard Smith2d406342011-10-22 21:10:00 +00006558 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6559 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006560
Craig Topper9798b932015-09-29 04:30:05 +00006561 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006562 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6563 // FIXME: remove this APValue copy.
6564 Result = APValue(V.data(), V.size());
6565 return true;
6566 }
Richard Smith2e312c82012-03-03 22:46:17 +00006567 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006568 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006569 Result = V;
6570 return true;
6571 }
Richard Smithfddd3842011-12-30 21:15:51 +00006572 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006573
Richard Smith2d406342011-10-22 21:10:00 +00006574 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006575 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006576 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006577 bool VisitInitListExpr(const InitListExpr *E);
6578 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006579 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006580 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006581 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006582 };
6583} // end anonymous namespace
6584
6585static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006586 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006587 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006588}
6589
George Burgess IV533ff002015-12-11 00:23:35 +00006590bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006591 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006592 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006593
Richard Smith161f09a2011-12-06 22:44:34 +00006594 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006595 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006596
Eli Friedmanc757de22011-03-25 00:43:55 +00006597 switch (E->getCastKind()) {
6598 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006599 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006600 if (SETy->isIntegerType()) {
6601 APSInt IntResult;
6602 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006603 return false;
6604 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006605 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006606 APFloat FloatResult(0.0);
6607 if (!EvaluateFloat(SE, FloatResult, Info))
6608 return false;
6609 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006610 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006611 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006612 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006613
6614 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006615 SmallVector<APValue, 4> Elts(NElts, Val);
6616 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006617 }
Eli Friedman803acb32011-12-22 03:51:45 +00006618 case CK_BitCast: {
6619 // Evaluate the operand into an APInt we can extract from.
6620 llvm::APInt SValInt;
6621 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6622 return false;
6623 // Extract the elements
6624 QualType EltTy = VTy->getElementType();
6625 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6626 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6627 SmallVector<APValue, 4> Elts;
6628 if (EltTy->isRealFloatingType()) {
6629 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006630 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006631 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006632 FloatEltSize = 80;
6633 for (unsigned i = 0; i < NElts; i++) {
6634 llvm::APInt Elt;
6635 if (BigEndian)
6636 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6637 else
6638 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006639 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006640 }
6641 } else if (EltTy->isIntegerType()) {
6642 for (unsigned i = 0; i < NElts; i++) {
6643 llvm::APInt Elt;
6644 if (BigEndian)
6645 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6646 else
6647 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6648 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6649 }
6650 } else {
6651 return Error(E);
6652 }
6653 return Success(Elts, E);
6654 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006655 default:
Richard Smith11562c52011-10-28 17:51:58 +00006656 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006657 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006658}
6659
Richard Smith2d406342011-10-22 21:10:00 +00006660bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006661VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006662 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006663 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006664 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006665
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006666 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006667 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006668
Eli Friedmanb9c71292012-01-03 23:24:20 +00006669 // The number of initializers can be less than the number of
6670 // vector elements. For OpenCL, this can be due to nested vector
Daniel Jasperffdee092017-05-02 19:21:42 +00006671 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00006672 // should be initialized with zeroes.
6673 unsigned CountInits = 0, CountElts = 0;
6674 while (CountElts < NumElements) {
6675 // Handle nested vector initialization.
Daniel Jasperffdee092017-05-02 19:21:42 +00006676 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006677 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006678 APValue v;
6679 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6680 return Error(E);
6681 unsigned vlen = v.getVectorLength();
Daniel Jasperffdee092017-05-02 19:21:42 +00006682 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00006683 Elements.push_back(v.getVectorElt(j));
6684 CountElts += vlen;
6685 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006686 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006687 if (CountInits < NumInits) {
6688 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006689 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006690 } else // trailing integer zero.
6691 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6692 Elements.push_back(APValue(sInt));
6693 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006694 } else {
6695 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006696 if (CountInits < NumInits) {
6697 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006698 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006699 } else // trailing float zero.
6700 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6701 Elements.push_back(APValue(f));
6702 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006703 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006704 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006705 }
Richard Smith2d406342011-10-22 21:10:00 +00006706 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006707}
6708
Richard Smith2d406342011-10-22 21:10:00 +00006709bool
Richard Smithfddd3842011-12-30 21:15:51 +00006710VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006711 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006712 QualType EltTy = VT->getElementType();
6713 APValue ZeroElement;
6714 if (EltTy->isIntegerType())
6715 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6716 else
6717 ZeroElement =
6718 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6719
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006720 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006721 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006722}
6723
Richard Smith2d406342011-10-22 21:10:00 +00006724bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006725 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006726 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006727}
6728
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006729//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006730// Array Evaluation
6731//===----------------------------------------------------------------------===//
6732
6733namespace {
6734 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006735 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006736 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006737 APValue &Result;
6738 public:
6739
Richard Smithd62306a2011-11-10 06:34:14 +00006740 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6741 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006742
6743 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006744 assert((V.isArray() || V.isLValue()) &&
6745 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006746 Result = V;
6747 return true;
6748 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006749
Richard Smithfddd3842011-12-30 21:15:51 +00006750 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006751 const ConstantArrayType *CAT =
6752 Info.Ctx.getAsConstantArrayType(E->getType());
6753 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006754 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006755
6756 Result = APValue(APValue::UninitArray(), 0,
6757 CAT->getSize().getZExtValue());
6758 if (!Result.hasArrayFiller()) return true;
6759
Richard Smithfddd3842011-12-30 21:15:51 +00006760 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006761 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006762 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006763 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006764 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006765 }
6766
Richard Smith52a980a2015-08-28 02:43:42 +00006767 bool VisitCallExpr(const CallExpr *E) {
6768 return handleCallExpr(E, Result, &This);
6769 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006770 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006771 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006772 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006773 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6774 const LValue &Subobject,
6775 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006776 };
6777} // end anonymous namespace
6778
Richard Smithd62306a2011-11-10 06:34:14 +00006779static bool EvaluateArray(const Expr *E, const LValue &This,
6780 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006781 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006782 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006783}
6784
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006785// Return true iff the given array filler may depend on the element index.
6786static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
6787 // For now, just whitelist non-class value-initialization and initialization
6788 // lists comprised of them.
6789 if (isa<ImplicitValueInitExpr>(FillerExpr))
6790 return false;
6791 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
6792 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
6793 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
6794 return true;
6795 }
6796 return false;
6797 }
6798 return true;
6799}
6800
Richard Smithf3e9e432011-11-07 09:22:26 +00006801bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6802 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6803 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006804 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006805
Richard Smithca2cfbf2011-12-22 01:07:19 +00006806 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6807 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006808 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006809 LValue LV;
6810 if (!EvaluateLValue(E->getInit(0), LV, Info))
6811 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006812 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006813 LV.moveInto(Val);
6814 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006815 }
6816
Richard Smith253c2a32012-01-27 01:14:48 +00006817 bool Success = true;
6818
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006819 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6820 "zero-initialized array shouldn't have any initialized elts");
6821 APValue Filler;
6822 if (Result.isArray() && Result.hasArrayFiller())
6823 Filler = Result.getArrayFiller();
6824
Richard Smith9543c5e2013-04-22 14:44:29 +00006825 unsigned NumEltsToInit = E->getNumInits();
6826 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006827 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006828
6829 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006830 // array element.
6831 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00006832 NumEltsToInit = NumElts;
6833
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006834 DEBUG(llvm::dbgs() << "The number of elements to initialize: " <<
6835 NumEltsToInit << ".\n");
6836
Richard Smith9543c5e2013-04-22 14:44:29 +00006837 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006838
6839 // If the array was previously zero-initialized, preserve the
6840 // zero-initialized values.
6841 if (!Filler.isUninit()) {
6842 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6843 Result.getArrayInitializedElt(I) = Filler;
6844 if (Result.hasArrayFiller())
6845 Result.getArrayFiller() = Filler;
6846 }
6847
Richard Smithd62306a2011-11-10 06:34:14 +00006848 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006849 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006850 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6851 const Expr *Init =
6852 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006853 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006854 Info, Subobject, Init) ||
6855 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006856 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006857 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006858 return false;
6859 Success = false;
6860 }
Richard Smithd62306a2011-11-10 06:34:14 +00006861 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006862
Richard Smith9543c5e2013-04-22 14:44:29 +00006863 if (!Result.hasArrayFiller())
6864 return Success;
6865
6866 // If we get here, we have a trivial filler, which we can just evaluate
6867 // once and splat over the rest of the array elements.
6868 assert(FillerExpr && "no array filler for incomplete init list");
6869 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6870 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006871}
6872
Richard Smith410306b2016-12-12 02:53:20 +00006873bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6874 if (E->getCommonExpr() &&
6875 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6876 Info, E->getCommonExpr()->getSourceExpr()))
6877 return false;
6878
6879 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6880
6881 uint64_t Elements = CAT->getSize().getZExtValue();
6882 Result = APValue(APValue::UninitArray(), Elements, Elements);
6883
6884 LValue Subobject = This;
6885 Subobject.addArray(Info, E, CAT);
6886
6887 bool Success = true;
6888 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6889 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6890 Info, Subobject, E->getSubExpr()) ||
6891 !HandleLValueArrayAdjustment(Info, E, Subobject,
6892 CAT->getElementType(), 1)) {
6893 if (!Info.noteFailure())
6894 return false;
6895 Success = false;
6896 }
6897 }
6898
6899 return Success;
6900}
6901
Richard Smith027bf112011-11-17 22:56:20 +00006902bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006903 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6904}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006905
Richard Smith9543c5e2013-04-22 14:44:29 +00006906bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6907 const LValue &Subobject,
6908 APValue *Value,
6909 QualType Type) {
6910 bool HadZeroInit = !Value->isUninit();
6911
6912 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6913 unsigned N = CAT->getSize().getZExtValue();
6914
6915 // Preserve the array filler if we had prior zero-initialization.
6916 APValue Filler =
6917 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6918 : APValue();
6919
6920 *Value = APValue(APValue::UninitArray(), N, N);
6921
6922 if (HadZeroInit)
6923 for (unsigned I = 0; I != N; ++I)
6924 Value->getArrayInitializedElt(I) = Filler;
6925
6926 // Initialize the elements.
6927 LValue ArrayElt = Subobject;
6928 ArrayElt.addArray(Info, E, CAT);
6929 for (unsigned I = 0; I != N; ++I)
6930 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6931 CAT->getElementType()) ||
6932 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6933 CAT->getElementType(), 1))
6934 return false;
6935
6936 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006937 }
Richard Smith027bf112011-11-17 22:56:20 +00006938
Richard Smith9543c5e2013-04-22 14:44:29 +00006939 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006940 return Error(E);
6941
Richard Smithb8348f52016-05-12 22:16:28 +00006942 return RecordExprEvaluator(Info, Subobject, *Value)
6943 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006944}
6945
Richard Smithf3e9e432011-11-07 09:22:26 +00006946//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006947// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006948//
6949// As a GNU extension, we support casting pointers to sufficiently-wide integer
6950// types and back in constant folding. Integer values are thus represented
6951// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006952//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006953
6954namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006955class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006956 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006957 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006958public:
Richard Smith2e312c82012-03-03 22:46:17 +00006959 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006960 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006961
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006962 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006963 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006964 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006965 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006966 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006967 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006968 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006969 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006970 return true;
6971 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006972 bool Success(const llvm::APSInt &SI, const Expr *E) {
6973 return Success(SI, E, Result);
6974 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006975
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006976 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00006977 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006978 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006979 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006980 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006981 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006982 Result.getInt().setIsUnsigned(
6983 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006984 return true;
6985 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006986 bool Success(const llvm::APInt &I, const Expr *E) {
6987 return Success(I, E, Result);
6988 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006989
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006990 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00006991 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006992 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006993 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006994 return true;
6995 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006996 bool Success(uint64_t Value, const Expr *E) {
6997 return Success(Value, E, Result);
6998 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006999
Ken Dyckdbc01912011-03-11 02:13:43 +00007000 bool Success(CharUnits Size, const Expr *E) {
7001 return Success(Size.getQuantity(), E);
7002 }
7003
Richard Smith2e312c82012-03-03 22:46:17 +00007004 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007005 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007006 Result = V;
7007 return true;
7008 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007009 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007010 }
Mike Stump11289f42009-09-09 15:08:12 +00007011
Richard Smithfddd3842011-12-30 21:15:51 +00007012 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007013
Peter Collingbournee9200682011-05-13 03:29:01 +00007014 //===--------------------------------------------------------------------===//
7015 // Visitor Methods
7016 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007017
Chris Lattner7174bf32008-07-12 00:38:25 +00007018 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007019 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007020 }
7021 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007022 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007023 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007024
7025 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7026 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007027 if (CheckReferencedDecl(E, E->getDecl()))
7028 return true;
7029
7030 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007031 }
7032 bool VisitMemberExpr(const MemberExpr *E) {
7033 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007034 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007035 return true;
7036 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007037
7038 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007039 }
7040
Peter Collingbournee9200682011-05-13 03:29:01 +00007041 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007042 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007043 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007044 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007045 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007046
Peter Collingbournee9200682011-05-13 03:29:01 +00007047 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007048 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007049
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007050 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007051 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007052 }
Mike Stump11289f42009-09-09 15:08:12 +00007053
Ted Kremeneke65b0862012-03-06 20:05:56 +00007054 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7055 return Success(E->getValue(), E);
7056 }
Richard Smith410306b2016-12-12 02:53:20 +00007057
7058 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7059 if (Info.ArrayInitIndex == uint64_t(-1)) {
7060 // We were asked to evaluate this subexpression independent of the
7061 // enclosing ArrayInitLoopExpr. We can't do that.
7062 Info.FFDiag(E);
7063 return false;
7064 }
7065 return Success(Info.ArrayInitIndex, E);
7066 }
Daniel Jasperffdee092017-05-02 19:21:42 +00007067
Richard Smith4ce706a2011-10-11 21:43:33 +00007068 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007069 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007070 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007071 }
7072
Douglas Gregor29c42f22012-02-24 07:38:34 +00007073 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7074 return Success(E->getValue(), E);
7075 }
7076
John Wiegley6242b6a2011-04-28 00:16:57 +00007077 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7078 return Success(E->getValue(), E);
7079 }
7080
John Wiegleyf9f65842011-04-25 06:54:41 +00007081 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7082 return Success(E->getValue(), E);
7083 }
7084
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007085 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007086 bool VisitUnaryImag(const UnaryOperator *E);
7087
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007088 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007089 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007090
Eli Friedman4e7a2412009-02-27 04:45:43 +00007091 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007092};
Chris Lattner05706e882008-07-11 18:11:29 +00007093} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007094
Richard Smith11562c52011-10-28 17:51:58 +00007095/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7096/// produce either the integer value or a pointer.
7097///
7098/// GCC has a heinous extension which folds casts between pointer types and
7099/// pointer-sized integral types. We support this by allowing the evaluation of
7100/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7101/// Some simple arithmetic on such values is supported (they are treated much
7102/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007103static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007104 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007105 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007106 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007107}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007108
Richard Smithf57d8cb2011-12-09 22:58:01 +00007109static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007110 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007111 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007112 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007113 if (!Val.isInt()) {
7114 // FIXME: It would be better to produce the diagnostic for casting
7115 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007116 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007117 return false;
7118 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007119 Result = Val.getInt();
7120 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007121}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007122
Richard Smithf57d8cb2011-12-09 22:58:01 +00007123/// Check whether the given declaration can be directly converted to an integral
7124/// rvalue. If not, no diagnostic is produced; there are other things we can
7125/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007126bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007127 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007128 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007129 // Check for signedness/width mismatches between E type and ECD value.
7130 bool SameSign = (ECD->getInitVal().isSigned()
7131 == E->getType()->isSignedIntegerOrEnumerationType());
7132 bool SameWidth = (ECD->getInitVal().getBitWidth()
7133 == Info.Ctx.getIntWidth(E->getType()));
7134 if (SameSign && SameWidth)
7135 return Success(ECD->getInitVal(), E);
7136 else {
7137 // Get rid of mismatch (otherwise Success assertions will fail)
7138 // by computing a new value matching the type of E.
7139 llvm::APSInt Val = ECD->getInitVal();
7140 if (!SameSign)
7141 Val.setIsSigned(!ECD->getInitVal().isSigned());
7142 if (!SameWidth)
7143 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7144 return Success(Val, E);
7145 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007146 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007147 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007148}
7149
Chris Lattner86ee2862008-10-06 06:40:35 +00007150/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7151/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007152static int EvaluateBuiltinClassifyType(const CallExpr *E,
7153 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007154 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007155 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007156 enum gcc_type_class {
7157 no_type_class = -1,
7158 void_type_class, integer_type_class, char_type_class,
7159 enumeral_type_class, boolean_type_class,
7160 pointer_type_class, reference_type_class, offset_type_class,
7161 real_type_class, complex_type_class,
7162 function_type_class, method_type_class,
7163 record_type_class, union_type_class,
7164 array_type_class, string_type_class,
7165 lang_type_class
7166 };
Mike Stump11289f42009-09-09 15:08:12 +00007167
7168 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007169 // ideal, however it is what gcc does.
7170 if (E->getNumArgs() == 0)
7171 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007172
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007173 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7174 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7175
7176 switch (CanTy->getTypeClass()) {
7177#define TYPE(ID, BASE)
7178#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7179#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7180#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7181#include "clang/AST/TypeNodes.def"
7182 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7183
7184 case Type::Builtin:
7185 switch (BT->getKind()) {
7186#define BUILTIN_TYPE(ID, SINGLETON_ID)
7187#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7188#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7189#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7190#include "clang/AST/BuiltinTypes.def"
7191 case BuiltinType::Void:
7192 return void_type_class;
7193
7194 case BuiltinType::Bool:
7195 return boolean_type_class;
7196
7197 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7198 case BuiltinType::UChar:
7199 case BuiltinType::UShort:
7200 case BuiltinType::UInt:
7201 case BuiltinType::ULong:
7202 case BuiltinType::ULongLong:
7203 case BuiltinType::UInt128:
7204 return integer_type_class;
7205
7206 case BuiltinType::NullPtr:
7207 return pointer_type_class;
7208
7209 case BuiltinType::WChar_U:
7210 case BuiltinType::Char16:
7211 case BuiltinType::Char32:
7212 case BuiltinType::ObjCId:
7213 case BuiltinType::ObjCClass:
7214 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007215#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7216 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007217#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007218 case BuiltinType::OCLSampler:
7219 case BuiltinType::OCLEvent:
7220 case BuiltinType::OCLClkEvent:
7221 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007222 case BuiltinType::OCLReserveID:
7223 case BuiltinType::Dependent:
7224 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7225 };
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007226 break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007227
7228 case Type::Enum:
7229 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7230 break;
7231
7232 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007233 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007234 break;
7235
7236 case Type::MemberPointer:
7237 if (CanTy->isMemberDataPointerType())
7238 return offset_type_class;
7239 else {
7240 // We expect member pointers to be either data or function pointers,
7241 // nothing else.
7242 assert(CanTy->isMemberFunctionPointerType());
7243 return method_type_class;
7244 }
7245
7246 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007247 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007248
7249 case Type::FunctionNoProto:
7250 case Type::FunctionProto:
7251 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7252
7253 case Type::Record:
7254 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7255 switch (RT->getDecl()->getTagKind()) {
7256 case TagTypeKind::TTK_Struct:
7257 case TagTypeKind::TTK_Class:
7258 case TagTypeKind::TTK_Interface:
7259 return record_type_class;
7260
7261 case TagTypeKind::TTK_Enum:
7262 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7263
7264 case TagTypeKind::TTK_Union:
7265 return union_type_class;
7266 }
7267 }
David Blaikie83d382b2011-09-23 05:06:16 +00007268 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007269
7270 case Type::ConstantArray:
7271 case Type::VariableArray:
7272 case Type::IncompleteArray:
7273 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7274
7275 case Type::BlockPointer:
7276 case Type::LValueReference:
7277 case Type::RValueReference:
7278 case Type::Vector:
7279 case Type::ExtVector:
7280 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007281 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007282 case Type::ObjCObject:
7283 case Type::ObjCInterface:
7284 case Type::ObjCObjectPointer:
7285 case Type::Pipe:
7286 case Type::Atomic:
7287 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7288 }
7289
7290 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007291}
7292
Richard Smith5fab0c92011-12-28 19:48:30 +00007293/// EvaluateBuiltinConstantPForLValue - Determine the result of
7294/// __builtin_constant_p when applied to the given lvalue.
7295///
7296/// An lvalue is only "constant" if it is a pointer or reference to the first
7297/// character of a string literal.
7298template<typename LValue>
7299static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007300 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007301 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7302}
7303
7304/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7305/// GCC as we can manage.
7306static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7307 QualType ArgType = Arg->getType();
7308
7309 // __builtin_constant_p always has one operand. The rules which gcc follows
7310 // are not precisely documented, but are as follows:
7311 //
7312 // - If the operand is of integral, floating, complex or enumeration type,
7313 // and can be folded to a known value of that type, it returns 1.
7314 // - If the operand and can be folded to a pointer to the first character
7315 // of a string literal (or such a pointer cast to an integral type), it
7316 // returns 1.
7317 //
7318 // Otherwise, it returns 0.
7319 //
7320 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7321 // its support for this does not currently work.
7322 if (ArgType->isIntegralOrEnumerationType()) {
7323 Expr::EvalResult Result;
7324 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7325 return false;
7326
7327 APValue &V = Result.Val;
7328 if (V.getKind() == APValue::Int)
7329 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007330 if (V.getKind() == APValue::LValue)
7331 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007332 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7333 return Arg->isEvaluatable(Ctx);
7334 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7335 LValue LV;
7336 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007337 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007338 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7339 : EvaluatePointer(Arg, LV, Info)) &&
7340 !Status.HasSideEffects)
7341 return EvaluateBuiltinConstantPForLValue(LV);
7342 }
7343
7344 // Anything else isn't considered to be sufficiently constant.
7345 return false;
7346}
7347
John McCall95007602010-05-10 23:27:23 +00007348/// Retrieves the "underlying object type" of the given expression,
7349/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007350static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007351 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7352 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007353 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007354 } else if (const Expr *E = B.get<const Expr*>()) {
7355 if (isa<CompoundLiteralExpr>(E))
7356 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007357 }
7358
7359 return QualType();
7360}
7361
George Burgess IV3a03fab2015-09-04 21:28:13 +00007362/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007363/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007364/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007365/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7366///
7367/// Always returns an RValue with a pointer representation.
7368static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7369 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7370
7371 auto *NoParens = E->IgnoreParens();
7372 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007373 if (Cast == nullptr)
7374 return NoParens;
7375
7376 // We only conservatively allow a few kinds of casts, because this code is
7377 // inherently a simple solution that seeks to support the common case.
7378 auto CastKind = Cast->getCastKind();
7379 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7380 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007381 return NoParens;
7382
7383 auto *SubExpr = Cast->getSubExpr();
7384 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7385 return NoParens;
7386 return ignorePointerCastsAndParens(SubExpr);
7387}
7388
George Burgess IVa51c4072015-10-16 01:49:01 +00007389/// Checks to see if the given LValue's Designator is at the end of the LValue's
7390/// record layout. e.g.
7391/// struct { struct { int a, b; } fst, snd; } obj;
7392/// obj.fst // no
7393/// obj.snd // yes
7394/// obj.fst.a // no
7395/// obj.fst.b // no
7396/// obj.snd.a // no
7397/// obj.snd.b // yes
7398///
7399/// Please note: this function is specialized for how __builtin_object_size
7400/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007401///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007402/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7403/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007404static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7405 assert(!LVal.Designator.Invalid);
7406
George Burgess IV4168d752016-06-27 19:40:41 +00007407 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7408 const RecordDecl *Parent = FD->getParent();
7409 Invalid = Parent->isInvalidDecl();
7410 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007411 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007412 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007413 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7414 };
7415
7416 auto &Base = LVal.getLValueBase();
7417 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7418 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007419 bool Invalid;
7420 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7421 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007422 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007423 for (auto *FD : IFD->chain()) {
7424 bool Invalid;
7425 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7426 return Invalid;
7427 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007428 }
7429 }
7430
George Burgess IVe3763372016-12-22 02:50:20 +00007431 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007432 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007433 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007434 // If we don't know the array bound, conservatively assume we're looking at
7435 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007436 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00007437 if (BaseType->isIncompleteArrayType())
7438 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7439 else
7440 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00007441 }
7442
7443 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7444 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007445 if (BaseType->isArrayType()) {
7446 // Because __builtin_object_size treats arrays as objects, we can ignore
7447 // the index iff this is the last array in the Designator.
7448 if (I + 1 == E)
7449 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007450 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7451 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007452 if (Index + 1 != CAT->getSize())
7453 return false;
7454 BaseType = CAT->getElementType();
7455 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007456 const auto *CT = BaseType->castAs<ComplexType>();
7457 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007458 if (Index != 1)
7459 return false;
7460 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007461 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007462 bool Invalid;
7463 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7464 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007465 BaseType = FD->getType();
7466 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007467 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007468 return false;
7469 }
7470 }
7471 return true;
7472}
7473
George Burgess IVe3763372016-12-22 02:50:20 +00007474/// Tests to see if the LValue has a user-specified designator (that isn't
7475/// necessarily valid). Note that this always returns 'true' if the LValue has
7476/// an unsized array as its first designator entry, because there's currently no
7477/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007478static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007479 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007480 return false;
7481
George Burgess IVe3763372016-12-22 02:50:20 +00007482 if (!LVal.Designator.Entries.empty())
7483 return LVal.Designator.isMostDerivedAnUnsizedArray();
7484
George Burgess IVa51c4072015-10-16 01:49:01 +00007485 if (!LVal.InvalidBase)
7486 return true;
7487
George Burgess IVe3763372016-12-22 02:50:20 +00007488 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7489 // the LValueBase.
7490 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7491 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007492}
7493
George Burgess IVe3763372016-12-22 02:50:20 +00007494/// Attempts to detect a user writing into a piece of memory that's impossible
7495/// to figure out the size of by just using types.
7496static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7497 const SubobjectDesignator &Designator = LVal.Designator;
7498 // Notes:
7499 // - Users can only write off of the end when we have an invalid base. Invalid
7500 // bases imply we don't know where the memory came from.
7501 // - We used to be a bit more aggressive here; we'd only be conservative if
7502 // the array at the end was flexible, or if it had 0 or 1 elements. This
7503 // broke some common standard library extensions (PR30346), but was
7504 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7505 // with some sort of whitelist. OTOH, it seems that GCC is always
7506 // conservative with the last element in structs (if it's an array), so our
7507 // current behavior is more compatible than a whitelisting approach would
7508 // be.
7509 return LVal.InvalidBase &&
7510 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7511 Designator.MostDerivedIsArrayElement &&
7512 isDesignatorAtObjectEnd(Ctx, LVal);
7513}
7514
7515/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7516/// Fails if the conversion would cause loss of precision.
7517static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7518 CharUnits &Result) {
7519 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7520 if (Int.ugt(CharUnitsMax))
7521 return false;
7522 Result = CharUnits::fromQuantity(Int.getZExtValue());
7523 return true;
7524}
7525
7526/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7527/// determine how many bytes exist from the beginning of the object to either
7528/// the end of the current subobject, or the end of the object itself, depending
7529/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007530///
George Burgess IVe3763372016-12-22 02:50:20 +00007531/// If this returns false, the value of Result is undefined.
7532static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7533 unsigned Type, const LValue &LVal,
7534 CharUnits &EndOffset) {
7535 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007536
George Burgess IV7fb7e362017-01-03 23:35:19 +00007537 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7538 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7539 return false;
7540 return HandleSizeof(Info, ExprLoc, Ty, Result);
7541 };
7542
George Burgess IVe3763372016-12-22 02:50:20 +00007543 // We want to evaluate the size of the entire object. This is a valid fallback
7544 // for when Type=1 and the designator is invalid, because we're asked for an
7545 // upper-bound.
7546 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7547 // Type=3 wants a lower bound, so we can't fall back to this.
7548 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007549 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007550
7551 llvm::APInt APEndOffset;
7552 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7553 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7554 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7555
7556 if (LVal.InvalidBase)
7557 return false;
7558
7559 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007560 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007561 }
7562
George Burgess IVe3763372016-12-22 02:50:20 +00007563 // We want to evaluate the size of a subobject.
7564 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007565
7566 // The following is a moderately common idiom in C:
7567 //
7568 // struct Foo { int a; char c[1]; };
7569 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7570 // strcpy(&F->c[0], Bar);
7571 //
George Burgess IVe3763372016-12-22 02:50:20 +00007572 // In order to not break too much legacy code, we need to support it.
7573 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7574 // If we can resolve this to an alloc_size call, we can hand that back,
7575 // because we know for certain how many bytes there are to write to.
7576 llvm::APInt APEndOffset;
7577 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7578 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7579 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7580
7581 // If we cannot determine the size of the initial allocation, then we can't
7582 // given an accurate upper-bound. However, we are still able to give
7583 // conservative lower-bounds for Type=3.
7584 if (Type == 1)
7585 return false;
7586 }
7587
7588 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007589 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007590 return false;
7591
George Burgess IVe3763372016-12-22 02:50:20 +00007592 // According to the GCC documentation, we want the size of the subobject
7593 // denoted by the pointer. But that's not quite right -- what we actually
7594 // want is the size of the immediately-enclosing array, if there is one.
7595 int64_t ElemsRemaining;
7596 if (Designator.MostDerivedIsArrayElement &&
7597 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7598 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7599 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7600 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7601 } else {
7602 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7603 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007604
George Burgess IVe3763372016-12-22 02:50:20 +00007605 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7606 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007607}
7608
George Burgess IVe3763372016-12-22 02:50:20 +00007609/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7610/// returns true and stores the result in @p Size.
7611///
7612/// If @p WasError is non-null, this will report whether the failure to evaluate
7613/// is to be treated as an Error in IntExprEvaluator.
7614static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7615 EvalInfo &Info, uint64_t &Size) {
7616 // Determine the denoted object.
7617 LValue LVal;
7618 {
7619 // The operand of __builtin_object_size is never evaluated for side-effects.
7620 // If there are any, but we can determine the pointed-to object anyway, then
7621 // ignore the side-effects.
7622 SpeculativeEvaluationRAII SpeculativeEval(Info);
7623 FoldOffsetRAII Fold(Info);
7624
7625 if (E->isGLValue()) {
7626 // It's possible for us to be given GLValues if we're called via
7627 // Expr::tryEvaluateObjectSize.
7628 APValue RVal;
7629 if (!EvaluateAsRValue(Info, E, RVal))
7630 return false;
7631 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007632 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7633 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007634 return false;
7635 }
7636
7637 // If we point to before the start of the object, there are no accessible
7638 // bytes.
7639 if (LVal.getLValueOffset().isNegative()) {
7640 Size = 0;
7641 return true;
7642 }
7643
7644 CharUnits EndOffset;
7645 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7646 return false;
7647
7648 // If we've fallen outside of the end offset, just pretend there's nothing to
7649 // write to/read from.
7650 if (EndOffset <= LVal.getLValueOffset())
7651 Size = 0;
7652 else
7653 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7654 return true;
John McCall95007602010-05-10 23:27:23 +00007655}
7656
Peter Collingbournee9200682011-05-13 03:29:01 +00007657bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007658 if (unsigned BuiltinOp = E->getBuiltinCallee())
7659 return VisitBuiltinCallExpr(E, BuiltinOp);
7660
7661 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7662}
7663
7664bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7665 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007666 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007667 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007668 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007669
7670 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007671 // The type was checked when we built the expression.
7672 unsigned Type =
7673 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7674 assert(Type <= 3 && "unexpected type");
7675
George Burgess IVe3763372016-12-22 02:50:20 +00007676 uint64_t Size;
7677 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7678 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007679
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007680 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007681 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007682
Richard Smith01ade172012-05-23 04:13:20 +00007683 // Expression had no side effects, but we couldn't statically determine the
7684 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007685 switch (Info.EvalMode) {
7686 case EvalInfo::EM_ConstantExpression:
7687 case EvalInfo::EM_PotentialConstantExpression:
7688 case EvalInfo::EM_ConstantFold:
7689 case EvalInfo::EM_EvaluateForOverflow:
7690 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007691 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007692 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007693 return Error(E);
7694 case EvalInfo::EM_ConstantExpressionUnevaluated:
7695 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007696 // Reduce it to a constant now.
7697 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007698 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007699
7700 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007701 }
7702
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007703 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007704 case Builtin::BI__builtin_bswap32:
7705 case Builtin::BI__builtin_bswap64: {
7706 APSInt Val;
7707 if (!EvaluateInteger(E->getArg(0), Val, Info))
7708 return false;
7709
7710 return Success(Val.byteSwap(), E);
7711 }
7712
Richard Smith8889a3d2013-06-13 06:26:32 +00007713 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007714 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007715
7716 // FIXME: BI__builtin_clrsb
7717 // FIXME: BI__builtin_clrsbl
7718 // FIXME: BI__builtin_clrsbll
7719
Richard Smith80b3c8e2013-06-13 05:04:16 +00007720 case Builtin::BI__builtin_clz:
7721 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007722 case Builtin::BI__builtin_clzll:
7723 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007724 APSInt Val;
7725 if (!EvaluateInteger(E->getArg(0), Val, Info))
7726 return false;
7727 if (!Val)
7728 return Error(E);
7729
7730 return Success(Val.countLeadingZeros(), E);
7731 }
7732
Richard Smith8889a3d2013-06-13 06:26:32 +00007733 case Builtin::BI__builtin_constant_p:
7734 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7735
Richard Smith80b3c8e2013-06-13 05:04:16 +00007736 case Builtin::BI__builtin_ctz:
7737 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007738 case Builtin::BI__builtin_ctzll:
7739 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007740 APSInt Val;
7741 if (!EvaluateInteger(E->getArg(0), Val, Info))
7742 return false;
7743 if (!Val)
7744 return Error(E);
7745
7746 return Success(Val.countTrailingZeros(), E);
7747 }
7748
Richard Smith8889a3d2013-06-13 06:26:32 +00007749 case Builtin::BI__builtin_eh_return_data_regno: {
7750 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7751 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7752 return Success(Operand, E);
7753 }
7754
7755 case Builtin::BI__builtin_expect:
7756 return Visit(E->getArg(0));
7757
7758 case Builtin::BI__builtin_ffs:
7759 case Builtin::BI__builtin_ffsl:
7760 case Builtin::BI__builtin_ffsll: {
7761 APSInt Val;
7762 if (!EvaluateInteger(E->getArg(0), Val, Info))
7763 return false;
7764
7765 unsigned N = Val.countTrailingZeros();
7766 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7767 }
7768
7769 case Builtin::BI__builtin_fpclassify: {
7770 APFloat Val(0.0);
7771 if (!EvaluateFloat(E->getArg(5), Val, Info))
7772 return false;
7773 unsigned Arg;
7774 switch (Val.getCategory()) {
7775 case APFloat::fcNaN: Arg = 0; break;
7776 case APFloat::fcInfinity: Arg = 1; break;
7777 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7778 case APFloat::fcZero: Arg = 4; break;
7779 }
7780 return Visit(E->getArg(Arg));
7781 }
7782
7783 case Builtin::BI__builtin_isinf_sign: {
7784 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007785 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007786 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7787 }
7788
Richard Smithea3019d2013-10-15 19:07:14 +00007789 case Builtin::BI__builtin_isinf: {
7790 APFloat Val(0.0);
7791 return EvaluateFloat(E->getArg(0), Val, Info) &&
7792 Success(Val.isInfinity() ? 1 : 0, E);
7793 }
7794
7795 case Builtin::BI__builtin_isfinite: {
7796 APFloat Val(0.0);
7797 return EvaluateFloat(E->getArg(0), Val, Info) &&
7798 Success(Val.isFinite() ? 1 : 0, E);
7799 }
7800
7801 case Builtin::BI__builtin_isnan: {
7802 APFloat Val(0.0);
7803 return EvaluateFloat(E->getArg(0), Val, Info) &&
7804 Success(Val.isNaN() ? 1 : 0, E);
7805 }
7806
7807 case Builtin::BI__builtin_isnormal: {
7808 APFloat Val(0.0);
7809 return EvaluateFloat(E->getArg(0), Val, Info) &&
7810 Success(Val.isNormal() ? 1 : 0, E);
7811 }
7812
Richard Smith8889a3d2013-06-13 06:26:32 +00007813 case Builtin::BI__builtin_parity:
7814 case Builtin::BI__builtin_parityl:
7815 case Builtin::BI__builtin_parityll: {
7816 APSInt Val;
7817 if (!EvaluateInteger(E->getArg(0), Val, Info))
7818 return false;
7819
7820 return Success(Val.countPopulation() % 2, E);
7821 }
7822
Richard Smith80b3c8e2013-06-13 05:04:16 +00007823 case Builtin::BI__builtin_popcount:
7824 case Builtin::BI__builtin_popcountl:
7825 case Builtin::BI__builtin_popcountll: {
7826 APSInt Val;
7827 if (!EvaluateInteger(E->getArg(0), Val, Info))
7828 return false;
7829
7830 return Success(Val.countPopulation(), E);
7831 }
7832
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007833 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007834 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007835 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007836 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007837 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007838 << /*isConstexpr*/0 << /*isConstructor*/0
7839 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007840 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007841 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007842 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007843 case Builtin::BI__builtin_strlen:
7844 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007845 // As an extension, we support __builtin_strlen() as a constant expression,
7846 // and support folding strlen() to a constant.
7847 LValue String;
7848 if (!EvaluatePointer(E->getArg(0), String, Info))
7849 return false;
7850
Richard Smith8110c9d2016-11-29 19:45:17 +00007851 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7852
Richard Smithe6c19f22013-11-15 02:10:04 +00007853 // Fast path: if it's a string literal, search the string value.
7854 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7855 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007856 // The string literal may have embedded null characters. Find the first
7857 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007858 StringRef Str = S->getBytes();
7859 int64_t Off = String.Offset.getQuantity();
7860 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007861 S->getCharByteWidth() == 1 &&
7862 // FIXME: Add fast-path for wchar_t too.
7863 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007864 Str = Str.substr(Off);
7865
7866 StringRef::size_type Pos = Str.find(0);
7867 if (Pos != StringRef::npos)
7868 Str = Str.substr(0, Pos);
7869
7870 return Success(Str.size(), E);
7871 }
7872
7873 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007874 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007875
7876 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007877 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7878 APValue Char;
7879 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7880 !Char.isInt())
7881 return false;
7882 if (!Char.getInt())
7883 return Success(Strlen, E);
7884 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7885 return false;
7886 }
7887 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007888
Richard Smithe151bab2016-11-11 23:43:35 +00007889 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007890 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007891 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007892 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007893 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007894 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007895 // A call to strlen is not a constant expression.
7896 if (Info.getLangOpts().CPlusPlus11)
7897 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7898 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007899 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007900 else
7901 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007902 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00007903 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007904 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007905 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007906 case Builtin::BI__builtin_wcsncmp:
7907 case Builtin::BI__builtin_memcmp:
7908 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007909 LValue String1, String2;
7910 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7911 !EvaluatePointer(E->getArg(1), String2, Info))
7912 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007913
7914 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7915
Richard Smithe151bab2016-11-11 23:43:35 +00007916 uint64_t MaxLength = uint64_t(-1);
7917 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007918 BuiltinOp != Builtin::BIwcscmp &&
7919 BuiltinOp != Builtin::BI__builtin_strcmp &&
7920 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007921 APSInt N;
7922 if (!EvaluateInteger(E->getArg(2), N, Info))
7923 return false;
7924 MaxLength = N.getExtValue();
7925 }
7926 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007927 BuiltinOp != Builtin::BIwmemcmp &&
7928 BuiltinOp != Builtin::BI__builtin_memcmp &&
7929 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007930 for (; MaxLength; --MaxLength) {
7931 APValue Char1, Char2;
7932 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7933 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7934 !Char1.isInt() || !Char2.isInt())
7935 return false;
7936 if (Char1.getInt() != Char2.getInt())
7937 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7938 if (StopAtNull && !Char1.getInt())
7939 return Success(0, E);
7940 assert(!(StopAtNull && !Char2.getInt()));
7941 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7942 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7943 return false;
7944 }
7945 // We hit the strncmp / memcmp limit.
7946 return Success(0, E);
7947 }
7948
Richard Smith01ba47d2012-04-13 00:45:38 +00007949 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007950 case Builtin::BI__atomic_is_lock_free:
7951 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007952 APSInt SizeVal;
7953 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7954 return false;
7955
7956 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7957 // of two less than the maximum inline atomic width, we know it is
7958 // lock-free. If the size isn't a power of two, or greater than the
7959 // maximum alignment where we promote atomics, we know it is not lock-free
7960 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7961 // the answer can only be determined at runtime; for example, 16-byte
7962 // atomics have lock-free implementations on some, but not all,
7963 // x86-64 processors.
7964
7965 // Check power-of-two.
7966 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007967 if (Size.isPowerOfTwo()) {
7968 // Check against inlining width.
7969 unsigned InlineWidthBits =
7970 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7971 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7972 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7973 Size == CharUnits::One() ||
7974 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7975 Expr::NPC_NeverValueDependent))
7976 // OK, we will inline appropriately-aligned operations of this size,
7977 // and _Atomic(T) is appropriately-aligned.
7978 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007979
Richard Smith01ba47d2012-04-13 00:45:38 +00007980 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7981 castAs<PointerType>()->getPointeeType();
7982 if (!PointeeType->isIncompleteType() &&
7983 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7984 // OK, we will inline operations on this object.
7985 return Success(1, E);
7986 }
7987 }
7988 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007989
Richard Smith01ba47d2012-04-13 00:45:38 +00007990 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7991 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007992 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00007993 case Builtin::BIomp_is_initial_device:
7994 // We can decide statically which value the runtime would return if called.
7995 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007996 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007997}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007998
Richard Smith8b3497e2011-10-31 01:37:14 +00007999static bool HasSameBase(const LValue &A, const LValue &B) {
8000 if (!A.getLValueBase())
8001 return !B.getLValueBase();
8002 if (!B.getLValueBase())
8003 return false;
8004
Richard Smithce40ad62011-11-12 22:28:03 +00008005 if (A.getLValueBase().getOpaqueValue() !=
8006 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008007 const Decl *ADecl = GetLValueBaseDecl(A);
8008 if (!ADecl)
8009 return false;
8010 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00008011 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00008012 return false;
8013 }
8014
8015 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00008016 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00008017}
8018
Richard Smithd20f1e62014-10-21 23:01:04 +00008019/// \brief Determine whether this is a pointer past the end of the complete
8020/// object referred to by the lvalue.
8021static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8022 const LValue &LV) {
8023 // A null pointer can be viewed as being "past the end" but we don't
8024 // choose to look at it that way here.
8025 if (!LV.getLValueBase())
8026 return false;
8027
8028 // If the designator is valid and refers to a subobject, we're not pointing
8029 // past the end.
8030 if (!LV.getLValueDesignator().Invalid &&
8031 !LV.getLValueDesignator().isOnePastTheEnd())
8032 return false;
8033
David Majnemerc378ca52015-08-29 08:32:55 +00008034 // A pointer to an incomplete type might be past-the-end if the type's size is
8035 // zero. We cannot tell because the type is incomplete.
8036 QualType Ty = getType(LV.getLValueBase());
8037 if (Ty->isIncompleteType())
8038 return true;
8039
Richard Smithd20f1e62014-10-21 23:01:04 +00008040 // We're a past-the-end pointer if we point to the byte after the object,
8041 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008042 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008043 return LV.getLValueOffset() == Size;
8044}
8045
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008046namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008047
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008048/// \brief Data recursive integer evaluator of certain binary operators.
8049///
8050/// We use a data recursive algorithm for binary operators so that we are able
8051/// to handle extreme cases of chained binary operators without causing stack
8052/// overflow.
8053class DataRecursiveIntBinOpEvaluator {
8054 struct EvalResult {
8055 APValue Val;
8056 bool Failed;
8057
8058 EvalResult() : Failed(false) { }
8059
8060 void swap(EvalResult &RHS) {
8061 Val.swap(RHS.Val);
8062 Failed = RHS.Failed;
8063 RHS.Failed = false;
8064 }
8065 };
8066
8067 struct Job {
8068 const Expr *E;
8069 EvalResult LHSResult; // meaningful only for binary operator expression.
8070 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008071
David Blaikie73726062015-08-12 23:09:24 +00008072 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008073 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008074
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008075 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008076 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008077 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008078
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008079 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008080 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008081 };
8082
8083 SmallVector<Job, 16> Queue;
8084
8085 IntExprEvaluator &IntEval;
8086 EvalInfo &Info;
8087 APValue &FinalResult;
8088
8089public:
8090 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8091 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8092
8093 /// \brief True if \param E is a binary operator that we are going to handle
8094 /// data recursively.
8095 /// We handle binary operators that are comma, logical, or that have operands
8096 /// with integral or enumeration type.
8097 static bool shouldEnqueue(const BinaryOperator *E) {
8098 return E->getOpcode() == BO_Comma ||
8099 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00008100 (E->isRValue() &&
8101 E->getType()->isIntegralOrEnumerationType() &&
8102 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008103 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008104 }
8105
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008106 bool Traverse(const BinaryOperator *E) {
8107 enqueue(E);
8108 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008109 while (!Queue.empty())
8110 process(PrevResult);
8111
8112 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008113
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008114 FinalResult.swap(PrevResult.Val);
8115 return true;
8116 }
8117
8118private:
8119 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8120 return IntEval.Success(Value, E, Result);
8121 }
8122 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8123 return IntEval.Success(Value, E, Result);
8124 }
8125 bool Error(const Expr *E) {
8126 return IntEval.Error(E);
8127 }
8128 bool Error(const Expr *E, diag::kind D) {
8129 return IntEval.Error(E, D);
8130 }
8131
8132 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8133 return Info.CCEDiag(E, D);
8134 }
8135
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008136 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8137 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008138 bool &SuppressRHSDiags);
8139
8140 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8141 const BinaryOperator *E, APValue &Result);
8142
8143 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8144 Result.Failed = !Evaluate(Result.Val, Info, E);
8145 if (Result.Failed)
8146 Result.Val = APValue();
8147 }
8148
Richard Trieuba4d0872012-03-21 23:30:30 +00008149 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008150
8151 void enqueue(const Expr *E) {
8152 E = E->IgnoreParens();
8153 Queue.resize(Queue.size()+1);
8154 Queue.back().E = E;
8155 Queue.back().Kind = Job::AnyExprKind;
8156 }
8157};
8158
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008159}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008160
8161bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008162 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008163 bool &SuppressRHSDiags) {
8164 if (E->getOpcode() == BO_Comma) {
8165 // Ignore LHS but note if we could not evaluate it.
8166 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008167 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008168 return true;
8169 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008170
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008171 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008172 bool LHSAsBool;
8173 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008174 // We were able to evaluate the LHS, see if we can get away with not
8175 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008176 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8177 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008178 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008179 }
8180 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008181 LHSResult.Failed = true;
8182
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008183 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008184 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008185 if (!Info.noteSideEffect())
8186 return false;
8187
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008188 // We can't evaluate the LHS; however, sometimes the result
8189 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8190 // Don't ignore RHS and suppress diagnostics from this arm.
8191 SuppressRHSDiags = true;
8192 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008193
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008194 return true;
8195 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008196
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008197 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8198 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008199
George Burgess IVa145e252016-05-25 22:38:36 +00008200 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008201 return false; // Ignore RHS;
8202
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008203 return true;
8204}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008205
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008206static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8207 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008208 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8209 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8210 // offsets.
8211 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8212 CharUnits &Offset = LVal.getLValueOffset();
8213 uint64_t Offset64 = Offset.getQuantity();
8214 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8215 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8216 : Offset64 + Index64);
8217}
8218
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008219bool DataRecursiveIntBinOpEvaluator::
8220 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8221 const BinaryOperator *E, APValue &Result) {
8222 if (E->getOpcode() == BO_Comma) {
8223 if (RHSResult.Failed)
8224 return false;
8225 Result = RHSResult.Val;
8226 return true;
8227 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008228
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008229 if (E->isLogicalOp()) {
8230 bool lhsResult, rhsResult;
8231 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8232 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Daniel Jasperffdee092017-05-02 19:21:42 +00008233
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008234 if (LHSIsOK) {
8235 if (RHSIsOK) {
8236 if (E->getOpcode() == BO_LOr)
8237 return Success(lhsResult || rhsResult, E, Result);
8238 else
8239 return Success(lhsResult && rhsResult, E, Result);
8240 }
8241 } else {
8242 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008243 // We can't evaluate the LHS; however, sometimes the result
8244 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8245 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008246 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008247 }
8248 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008249
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008250 return false;
8251 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008252
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008253 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8254 E->getRHS()->getType()->isIntegralOrEnumerationType());
Daniel Jasperffdee092017-05-02 19:21:42 +00008255
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008256 if (LHSResult.Failed || RHSResult.Failed)
8257 return false;
Daniel Jasperffdee092017-05-02 19:21:42 +00008258
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008259 const APValue &LHSVal = LHSResult.Val;
8260 const APValue &RHSVal = RHSResult.Val;
Daniel Jasperffdee092017-05-02 19:21:42 +00008261
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008262 // Handle cases like (unsigned long)&a + 4.
8263 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8264 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008265 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008266 return true;
8267 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008268
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008269 // Handle cases like 4 + (unsigned long)&a
8270 if (E->getOpcode() == BO_Add &&
8271 RHSVal.isLValue() && LHSVal.isInt()) {
8272 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008273 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008274 return true;
8275 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008276
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008277 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8278 // Handle (intptr_t)&&A - (intptr_t)&&B.
8279 if (!LHSVal.getLValueOffset().isZero() ||
8280 !RHSVal.getLValueOffset().isZero())
8281 return false;
8282 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8283 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8284 if (!LHSExpr || !RHSExpr)
8285 return false;
8286 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8287 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8288 if (!LHSAddrExpr || !RHSAddrExpr)
8289 return false;
8290 // Make sure both labels come from the same function.
8291 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8292 RHSAddrExpr->getLabel()->getDeclContext())
8293 return false;
8294 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8295 return true;
8296 }
Richard Smith43e77732013-05-07 04:50:00 +00008297
8298 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008299 if (!LHSVal.isInt() || !RHSVal.isInt())
8300 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008301
8302 // Set up the width and signedness manually, in case it can't be deduced
8303 // from the operation we're performing.
8304 // FIXME: Don't do this in the cases where we can deduce it.
8305 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8306 E->getType()->isUnsignedIntegerOrEnumerationType());
8307 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8308 RHSVal.getInt(), Value))
8309 return false;
8310 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008311}
8312
Richard Trieuba4d0872012-03-21 23:30:30 +00008313void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008314 Job &job = Queue.back();
Daniel Jasperffdee092017-05-02 19:21:42 +00008315
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008316 switch (job.Kind) {
8317 case Job::AnyExprKind: {
8318 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8319 if (shouldEnqueue(Bop)) {
8320 job.Kind = Job::BinOpKind;
8321 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008322 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008323 }
8324 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008325
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008326 EvaluateExpr(job.E, Result);
8327 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008328 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008329 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008330
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008331 case Job::BinOpKind: {
8332 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008333 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008334 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008335 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008336 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008337 }
8338 if (SuppressRHSDiags)
8339 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008340 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008341 job.Kind = Job::BinOpVisitedLHSKind;
8342 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008343 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008344 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008345
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008346 case Job::BinOpVisitedLHSKind: {
8347 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8348 EvalResult RHS;
8349 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008350 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008351 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008352 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008353 }
8354 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008355
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008356 llvm_unreachable("Invalid Job::Kind!");
8357}
8358
George Burgess IV8c892b52016-05-25 22:31:54 +00008359namespace {
8360/// Used when we determine that we should fail, but can keep evaluating prior to
8361/// noting that we had a failure.
8362class DelayedNoteFailureRAII {
8363 EvalInfo &Info;
8364 bool NoteFailure;
8365
8366public:
8367 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8368 : Info(Info), NoteFailure(NoteFailure) {}
8369 ~DelayedNoteFailureRAII() {
8370 if (NoteFailure) {
8371 bool ContinueAfterFailure = Info.noteFailure();
8372 (void)ContinueAfterFailure;
8373 assert(ContinueAfterFailure &&
8374 "Shouldn't have kept evaluating on failure.");
8375 }
8376 }
8377};
8378}
8379
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008380bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008381 // We don't call noteFailure immediately because the assignment happens after
8382 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008383 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008384 return Error(E);
8385
George Burgess IV8c892b52016-05-25 22:31:54 +00008386 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008387 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8388 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008389
Anders Carlssonacc79812008-11-16 07:17:21 +00008390 QualType LHSTy = E->getLHS()->getType();
8391 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008392
Chandler Carruthb29a7432014-10-11 11:03:30 +00008393 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008394 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008395 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008396 if (E->isAssignmentOp()) {
8397 LValue LV;
8398 EvaluateLValue(E->getLHS(), LV, Info);
8399 LHSOK = false;
8400 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008401 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8402 if (LHSOK) {
8403 LHS.makeComplexFloat();
8404 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8405 }
8406 } else {
8407 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8408 }
George Burgess IVa145e252016-05-25 22:38:36 +00008409 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008410 return false;
8411
Chandler Carruthb29a7432014-10-11 11:03:30 +00008412 if (E->getRHS()->getType()->isRealFloatingType()) {
8413 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8414 return false;
8415 RHS.makeComplexFloat();
8416 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8417 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008418 return false;
8419
8420 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008421 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008422 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008423 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008424 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8425
John McCalle3027922010-08-25 11:45:40 +00008426 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008427 return Success((CR_r == APFloat::cmpEqual &&
8428 CR_i == APFloat::cmpEqual), E);
8429 else {
John McCalle3027922010-08-25 11:45:40 +00008430 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008431 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008432 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008433 CR_r == APFloat::cmpLessThan ||
8434 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008435 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008436 CR_i == APFloat::cmpLessThan ||
8437 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008438 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008439 } else {
John McCalle3027922010-08-25 11:45:40 +00008440 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008441 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8442 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8443 else {
John McCalle3027922010-08-25 11:45:40 +00008444 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008445 "Invalid compex comparison.");
8446 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8447 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8448 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008449 }
8450 }
Mike Stump11289f42009-09-09 15:08:12 +00008451
Anders Carlssonacc79812008-11-16 07:17:21 +00008452 if (LHSTy->isRealFloatingType() &&
8453 RHSTy->isRealFloatingType()) {
8454 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008455
Richard Smith253c2a32012-01-27 01:14:48 +00008456 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008457 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008458 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008459
Richard Smith253c2a32012-01-27 01:14:48 +00008460 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008461 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008462
Anders Carlssonacc79812008-11-16 07:17:21 +00008463 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008464
Anders Carlssonacc79812008-11-16 07:17:21 +00008465 switch (E->getOpcode()) {
8466 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008467 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008468 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008469 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008470 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008471 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008472 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008473 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008474 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008475 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008476 E);
John McCalle3027922010-08-25 11:45:40 +00008477 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008478 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008479 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008480 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008481 || CR == APFloat::cmpLessThan
8482 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008483 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008484 }
Mike Stump11289f42009-09-09 15:08:12 +00008485
Eli Friedmana38da572009-04-28 19:17:36 +00008486 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008487 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008488 LValue LHSValue, RHSValue;
8489
8490 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008491 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008492 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008493
Richard Smith253c2a32012-01-27 01:14:48 +00008494 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008495 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008496
Richard Smith8b3497e2011-10-31 01:37:14 +00008497 // Reject differing bases from the normal codepath; we special-case
8498 // comparisons to null.
8499 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008500 if (E->getOpcode() == BO_Sub) {
8501 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008502 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008503 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008504 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008505 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008506 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008507 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008508 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8509 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8510 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008511 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008512 // Make sure both labels come from the same function.
8513 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8514 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008515 return Error(E);
8516 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008517 }
Richard Smith83c68212011-10-31 05:11:32 +00008518 // Inequalities and subtractions between unrelated pointers have
8519 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008520 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008521 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008522 // A constant address may compare equal to the address of a symbol.
8523 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008524 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008525 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8526 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008527 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008528 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008529 // distinct addresses. In clang, the result of such a comparison is
8530 // unspecified, so it is not a constant expression. However, we do know
8531 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008532 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8533 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008534 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008535 // We can't tell whether weak symbols will end up pointing to the same
8536 // object.
8537 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008538 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008539 // We can't compare the address of the start of one object with the
8540 // past-the-end address of another object, per C++ DR1652.
8541 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8542 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8543 (RHSValue.Base && RHSValue.Offset.isZero() &&
8544 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8545 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008546 // We can't tell whether an object is at the same address as another
8547 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008548 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8549 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008550 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008551 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008552 // (Note that clang defaults to -fmerge-all-constants, which can
8553 // lead to inconsistent results for comparisons involving the address
8554 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008555 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008556 }
Eli Friedman64004332009-03-23 04:38:34 +00008557
Richard Smith1b470412012-02-01 08:10:20 +00008558 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8559 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8560
Richard Smith84f6dcf2012-02-02 01:16:57 +00008561 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8562 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8563
John McCalle3027922010-08-25 11:45:40 +00008564 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008565 // C++11 [expr.add]p6:
8566 // Unless both pointers point to elements of the same array object, or
8567 // one past the last element of the array object, the behavior is
8568 // undefined.
8569 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8570 !AreElementsOfSameArray(getType(LHSValue.Base),
8571 LHSDesignator, RHSDesignator))
8572 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8573
Chris Lattner882bdf22010-04-20 17:13:14 +00008574 QualType Type = E->getLHS()->getType();
8575 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008576
Richard Smithd62306a2011-11-10 06:34:14 +00008577 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008578 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008579 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008580
Richard Smith84c6b3d2013-09-10 21:34:14 +00008581 // As an extension, a type may have zero size (empty struct or union in
8582 // C, array of zero length). Pointer subtraction in such cases has
8583 // undefined behavior, so is not constant.
8584 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008585 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008586 << ElementType;
8587 return false;
8588 }
8589
Richard Smith1b470412012-02-01 08:10:20 +00008590 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8591 // and produce incorrect results when it overflows. Such behavior
8592 // appears to be non-conforming, but is common, so perhaps we should
8593 // assume the standard intended for such cases to be undefined behavior
8594 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008595
Richard Smith1b470412012-02-01 08:10:20 +00008596 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8597 // overflow in the final conversion to ptrdiff_t.
8598 APSInt LHS(
8599 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8600 APSInt RHS(
8601 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8602 APSInt ElemSize(
8603 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8604 APSInt TrueResult = (LHS - RHS) / ElemSize;
8605 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8606
Richard Smith0c6124b2015-12-03 01:36:22 +00008607 if (Result.extend(65) != TrueResult &&
8608 !HandleOverflow(Info, E, TrueResult, E->getType()))
8609 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008610 return Success(Result, E);
8611 }
Richard Smithde21b242012-01-31 06:41:30 +00008612
8613 // C++11 [expr.rel]p3:
8614 // Pointers to void (after pointer conversions) can be compared, with a
8615 // result defined as follows: If both pointers represent the same
8616 // address or are both the null pointer value, the result is true if the
8617 // operator is <= or >= and false otherwise; otherwise the result is
8618 // unspecified.
8619 // We interpret this as applying to pointers to *cv* void.
8620 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008621 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008622 CCEDiag(E, diag::note_constexpr_void_comparison);
8623
Richard Smith84f6dcf2012-02-02 01:16:57 +00008624 // C++11 [expr.rel]p2:
8625 // - If two pointers point to non-static data members of the same object,
8626 // or to subobjects or array elements fo such members, recursively, the
8627 // pointer to the later declared member compares greater provided the
8628 // two members have the same access control and provided their class is
8629 // not a union.
8630 // [...]
8631 // - Otherwise pointer comparisons are unspecified.
8632 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8633 E->isRelationalOp()) {
8634 bool WasArrayIndex;
8635 unsigned Mismatch =
8636 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8637 RHSDesignator, WasArrayIndex);
8638 // At the point where the designators diverge, the comparison has a
8639 // specified value if:
8640 // - we are comparing array indices
8641 // - we are comparing fields of a union, or fields with the same access
8642 // Otherwise, the result is unspecified and thus the comparison is not a
8643 // constant expression.
8644 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8645 Mismatch < RHSDesignator.Entries.size()) {
8646 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8647 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8648 if (!LF && !RF)
8649 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8650 else if (!LF)
8651 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8652 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8653 << RF->getParent() << RF;
8654 else if (!RF)
8655 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8656 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8657 << LF->getParent() << LF;
8658 else if (!LF->getParent()->isUnion() &&
8659 LF->getAccess() != RF->getAccess())
8660 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8661 << LF << LF->getAccess() << RF << RF->getAccess()
8662 << LF->getParent();
8663 }
8664 }
8665
Eli Friedman6c31cb42012-04-16 04:30:08 +00008666 // The comparison here must be unsigned, and performed with the same
8667 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008668 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8669 uint64_t CompareLHS = LHSOffset.getQuantity();
8670 uint64_t CompareRHS = RHSOffset.getQuantity();
8671 assert(PtrSize <= 64 && "Unexpected pointer width");
8672 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8673 CompareLHS &= Mask;
8674 CompareRHS &= Mask;
8675
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008676 // If there is a base and this is a relational operator, we can only
8677 // compare pointers within the object in question; otherwise, the result
8678 // depends on where the object is located in memory.
8679 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8680 QualType BaseTy = getType(LHSValue.Base);
8681 if (BaseTy->isIncompleteType())
8682 return Error(E);
8683 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8684 uint64_t OffsetLimit = Size.getQuantity();
8685 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8686 return Error(E);
8687 }
8688
Richard Smith8b3497e2011-10-31 01:37:14 +00008689 switch (E->getOpcode()) {
8690 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008691 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8692 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8693 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8694 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8695 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8696 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008697 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008698 }
8699 }
Richard Smith7bb00672012-02-01 01:42:44 +00008700
8701 if (LHSTy->isMemberPointerType()) {
8702 assert(E->isEqualityOp() && "unexpected member pointer operation");
8703 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8704
8705 MemberPtr LHSValue, RHSValue;
8706
8707 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008708 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008709 return false;
8710
8711 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8712 return false;
8713
8714 // C++11 [expr.eq]p2:
8715 // If both operands are null, they compare equal. Otherwise if only one is
8716 // null, they compare unequal.
8717 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8718 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8719 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8720 }
8721
8722 // Otherwise if either is a pointer to a virtual member function, the
8723 // result is unspecified.
8724 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8725 if (MD->isVirtual())
8726 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8727 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8728 if (MD->isVirtual())
8729 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8730
8731 // Otherwise they compare equal if and only if they would refer to the
8732 // same member of the same most derived object or the same subobject if
8733 // they were dereferenced with a hypothetical object of the associated
8734 // class type.
8735 bool Equal = LHSValue == RHSValue;
8736 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8737 }
8738
Richard Smithab44d9b2012-02-14 22:35:28 +00008739 if (LHSTy->isNullPtrType()) {
8740 assert(E->isComparisonOp() && "unexpected nullptr operation");
8741 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8742 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8743 // are compared, the result is true of the operator is <=, >= or ==, and
8744 // false otherwise.
8745 BinaryOperator::Opcode Opcode = E->getOpcode();
8746 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8747 }
8748
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008749 assert((!LHSTy->isIntegralOrEnumerationType() ||
8750 !RHSTy->isIntegralOrEnumerationType()) &&
8751 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8752 // We can't continue from here for non-integral types.
8753 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008754}
8755
Peter Collingbournee190dee2011-03-11 19:24:49 +00008756/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8757/// a result as the expression's type.
8758bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8759 const UnaryExprOrTypeTraitExpr *E) {
8760 switch(E->getKind()) {
8761 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008762 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008763 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008764 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008765 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008766 }
Eli Friedman64004332009-03-23 04:38:34 +00008767
Peter Collingbournee190dee2011-03-11 19:24:49 +00008768 case UETT_VecStep: {
8769 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008770
Peter Collingbournee190dee2011-03-11 19:24:49 +00008771 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008772 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008773
Peter Collingbournee190dee2011-03-11 19:24:49 +00008774 // The vec_step built-in functions that take a 3-component
8775 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8776 if (n == 3)
8777 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008778
Peter Collingbournee190dee2011-03-11 19:24:49 +00008779 return Success(n, E);
8780 } else
8781 return Success(1, E);
8782 }
8783
8784 case UETT_SizeOf: {
8785 QualType SrcTy = E->getTypeOfArgument();
8786 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8787 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008788 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8789 SrcTy = Ref->getPointeeType();
8790
Richard Smithd62306a2011-11-10 06:34:14 +00008791 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008792 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008793 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008794 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008795 }
Alexey Bataev00396512015-07-02 03:40:19 +00008796 case UETT_OpenMPRequiredSimdAlign:
8797 assert(E->isArgumentType());
8798 return Success(
8799 Info.Ctx.toCharUnitsFromBits(
8800 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8801 .getQuantity(),
8802 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008803 }
8804
8805 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008806}
8807
Peter Collingbournee9200682011-05-13 03:29:01 +00008808bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008809 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008810 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008811 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008812 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008813 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008814 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008815 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008816 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008817 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008818 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008819 APSInt IdxResult;
8820 if (!EvaluateInteger(Idx, IdxResult, Info))
8821 return false;
8822 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8823 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008824 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008825 CurrentType = AT->getElementType();
8826 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8827 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008828 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008829 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008830
James Y Knight7281c352015-12-29 22:31:18 +00008831 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008832 FieldDecl *MemberDecl = ON.getField();
8833 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008834 if (!RT)
8835 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008836 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008837 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008838 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008839 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008840 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008841 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008842 CurrentType = MemberDecl->getType().getNonReferenceType();
8843 break;
8844 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008845
James Y Knight7281c352015-12-29 22:31:18 +00008846 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008847 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008848
James Y Knight7281c352015-12-29 22:31:18 +00008849 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008850 CXXBaseSpecifier *BaseSpec = ON.getBase();
8851 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008852 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008853
8854 // Find the layout of the class whose base we are looking into.
8855 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008856 if (!RT)
8857 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008858 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008859 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008860 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8861
8862 // Find the base class itself.
8863 CurrentType = BaseSpec->getType();
8864 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8865 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008866 return Error(OOE);
Daniel Jasperffdee092017-05-02 19:21:42 +00008867
Douglas Gregord1702062010-04-29 00:18:15 +00008868 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008869 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008870 break;
8871 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008872 }
8873 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008874 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008875}
8876
Chris Lattnere13042c2008-07-11 19:10:17 +00008877bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008878 switch (E->getOpcode()) {
8879 default:
8880 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8881 // See C99 6.6p3.
8882 return Error(E);
8883 case UO_Extension:
8884 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8885 // If so, we could clear the diagnostic ID.
8886 return Visit(E->getSubExpr());
8887 case UO_Plus:
8888 // The result is just the value.
8889 return Visit(E->getSubExpr());
8890 case UO_Minus: {
8891 if (!Visit(E->getSubExpr()))
Aaron Ballmana5038552018-01-09 13:07:03 +00008892 return false;
8893 if (!Result.isInt()) return Error(E);
8894 const APSInt &Value = Result.getInt();
8895 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
8896 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8897 E->getType()))
8898 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008899 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008900 }
8901 case UO_Not: {
8902 if (!Visit(E->getSubExpr()))
8903 return false;
8904 if (!Result.isInt()) return Error(E);
8905 return Success(~Result.getInt(), E);
8906 }
8907 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008908 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008909 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008910 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008911 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008912 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008913 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008914}
Mike Stump11289f42009-09-09 15:08:12 +00008915
Chris Lattner477c4be2008-07-12 01:15:53 +00008916/// HandleCast - This is used to evaluate implicit or explicit casts where the
8917/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008918bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8919 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008920 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008921 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008922
Eli Friedmanc757de22011-03-25 00:43:55 +00008923 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008924 case CK_BaseToDerived:
8925 case CK_DerivedToBase:
8926 case CK_UncheckedDerivedToBase:
8927 case CK_Dynamic:
8928 case CK_ToUnion:
8929 case CK_ArrayToPointerDecay:
8930 case CK_FunctionToPointerDecay:
8931 case CK_NullToPointer:
8932 case CK_NullToMemberPointer:
8933 case CK_BaseToDerivedMemberPointer:
8934 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008935 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008936 case CK_ConstructorConversion:
8937 case CK_IntegralToPointer:
8938 case CK_ToVoid:
8939 case CK_VectorSplat:
8940 case CK_IntegralToFloating:
8941 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008942 case CK_CPointerToObjCPointerCast:
8943 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008944 case CK_AnyPointerToBlockPointerCast:
8945 case CK_ObjCObjectLValueCast:
8946 case CK_FloatingRealToComplex:
8947 case CK_FloatingComplexToReal:
8948 case CK_FloatingComplexCast:
8949 case CK_FloatingComplexToIntegralComplex:
8950 case CK_IntegralRealToComplex:
8951 case CK_IntegralComplexCast:
8952 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008953 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008954 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008955 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008956 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008957 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008958 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008959 llvm_unreachable("invalid cast kind for integral value");
8960
Eli Friedman9faf2f92011-03-25 19:07:11 +00008961 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008962 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008963 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008964 case CK_ARCProduceObject:
8965 case CK_ARCConsumeObject:
8966 case CK_ARCReclaimReturnedObject:
8967 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008968 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008969 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008970
Richard Smith4ef685b2012-01-17 21:17:26 +00008971 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008972 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008973 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008974 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008975 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008976
8977 case CK_MemberPointerToBoolean:
8978 case CK_PointerToBoolean:
8979 case CK_IntegralToBoolean:
8980 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008981 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008982 case CK_FloatingComplexToBoolean:
8983 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008984 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008985 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008986 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008987 uint64_t IntResult = BoolResult;
8988 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8989 IntResult = (uint64_t)-1;
8990 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008991 }
8992
Eli Friedmanc757de22011-03-25 00:43:55 +00008993 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008994 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008995 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008996
Eli Friedman742421e2009-02-20 01:15:07 +00008997 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008998 // Allow casts of address-of-label differences if they are no-ops
8999 // or narrowing. (The narrowing case isn't actually guaranteed to
9000 // be constant-evaluatable except in some narrow cases which are hard
9001 // to detect here. We let it through on the assumption the user knows
9002 // what they are doing.)
9003 if (Result.isAddrLabelDiff())
9004 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00009005 // Only allow casts of lvalues if they are lossless.
9006 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9007 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009008
Richard Smith911e1422012-01-30 22:27:01 +00009009 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9010 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00009011 }
Mike Stump11289f42009-09-09 15:08:12 +00009012
Eli Friedmanc757de22011-03-25 00:43:55 +00009013 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00009014 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9015
John McCall45d55e42010-05-07 21:00:08 +00009016 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00009017 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009018 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009019
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009020 if (LV.getLValueBase()) {
9021 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009022 // FIXME: Allow a larger integer size than the pointer size, and allow
9023 // narrowing back down to pointer width in subsequent integral casts.
9024 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009025 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009026 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009027
Richard Smithcf74da72011-11-16 07:18:12 +00009028 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009029 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009030 return true;
9031 }
9032
Yaxun Liu402804b2016-12-15 08:09:08 +00009033 uint64_t V;
9034 if (LV.isNullPointer())
9035 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9036 else
9037 V = LV.getLValueOffset().getQuantity();
9038
9039 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00009040 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009041 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009042
Eli Friedmanc757de22011-03-25 00:43:55 +00009043 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009044 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009045 if (!EvaluateComplex(SubExpr, C, Info))
9046 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009047 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009048 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009049
Eli Friedmanc757de22011-03-25 00:43:55 +00009050 case CK_FloatingToIntegral: {
9051 APFloat F(0.0);
9052 if (!EvaluateFloat(SubExpr, F, Info))
9053 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009054
Richard Smith357362d2011-12-13 06:39:58 +00009055 APSInt Value;
9056 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9057 return false;
9058 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009059 }
9060 }
Mike Stump11289f42009-09-09 15:08:12 +00009061
Eli Friedmanc757de22011-03-25 00:43:55 +00009062 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009063}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009064
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009065bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9066 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009067 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009068 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9069 return false;
9070 if (!LV.isComplexInt())
9071 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009072 return Success(LV.getComplexIntReal(), E);
9073 }
9074
9075 return Visit(E->getSubExpr());
9076}
9077
Eli Friedman4e7a2412009-02-27 04:45:43 +00009078bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009079 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009080 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009081 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9082 return false;
9083 if (!LV.isComplexInt())
9084 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009085 return Success(LV.getComplexIntImag(), E);
9086 }
9087
Richard Smith4a678122011-10-24 18:44:57 +00009088 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009089 return Success(0, E);
9090}
9091
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009092bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9093 return Success(E->getPackLength(), E);
9094}
9095
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009096bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9097 return Success(E->getValue(), E);
9098}
9099
Chris Lattner05706e882008-07-11 18:11:29 +00009100//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009101// Float Evaluation
9102//===----------------------------------------------------------------------===//
9103
9104namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009105class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009106 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009107 APFloat &Result;
9108public:
9109 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009110 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009111
Richard Smith2e312c82012-03-03 22:46:17 +00009112 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009113 Result = V.getFloat();
9114 return true;
9115 }
Eli Friedman24c01542008-08-22 00:06:13 +00009116
Richard Smithfddd3842011-12-30 21:15:51 +00009117 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009118 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9119 return true;
9120 }
9121
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009122 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009123
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009124 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009125 bool VisitBinaryOperator(const BinaryOperator *E);
9126 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009127 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009128
John McCallb1fb0d32010-05-07 22:08:54 +00009129 bool VisitUnaryReal(const UnaryOperator *E);
9130 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009131
Richard Smithfddd3842011-12-30 21:15:51 +00009132 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009133};
9134} // end anonymous namespace
9135
9136static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009137 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009138 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009139}
9140
Jay Foad39c79802011-01-12 09:06:06 +00009141static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009142 QualType ResultTy,
9143 const Expr *Arg,
9144 bool SNaN,
9145 llvm::APFloat &Result) {
9146 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9147 if (!S) return false;
9148
9149 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9150
9151 llvm::APInt fill;
9152
9153 // Treat empty strings as if they were zero.
9154 if (S->getString().empty())
9155 fill = llvm::APInt(32, 0);
9156 else if (S->getString().getAsInteger(0, fill))
9157 return false;
9158
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009159 if (Context.getTargetInfo().isNan2008()) {
9160 if (SNaN)
9161 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9162 else
9163 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9164 } else {
9165 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9166 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9167 // a different encoding to what became a standard in 2008, and for pre-
9168 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9169 // sNaN. This is now known as "legacy NaN" encoding.
9170 if (SNaN)
9171 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9172 else
9173 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9174 }
9175
John McCall16291492010-02-28 13:00:19 +00009176 return true;
9177}
9178
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009179bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009180 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009181 default:
9182 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9183
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009184 case Builtin::BI__builtin_huge_val:
9185 case Builtin::BI__builtin_huge_valf:
9186 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009187 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009188 case Builtin::BI__builtin_inf:
9189 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009190 case Builtin::BI__builtin_infl:
9191 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009192 const llvm::fltSemantics &Sem =
9193 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009194 Result = llvm::APFloat::getInf(Sem);
9195 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009196 }
Mike Stump11289f42009-09-09 15:08:12 +00009197
John McCall16291492010-02-28 13:00:19 +00009198 case Builtin::BI__builtin_nans:
9199 case Builtin::BI__builtin_nansf:
9200 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009201 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009202 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9203 true, Result))
9204 return Error(E);
9205 return true;
John McCall16291492010-02-28 13:00:19 +00009206
Chris Lattner0b7282e2008-10-06 06:31:58 +00009207 case Builtin::BI__builtin_nan:
9208 case Builtin::BI__builtin_nanf:
9209 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009210 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +00009211 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009212 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009213 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9214 false, Result))
9215 return Error(E);
9216 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009217
9218 case Builtin::BI__builtin_fabs:
9219 case Builtin::BI__builtin_fabsf:
9220 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009221 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009222 if (!EvaluateFloat(E->getArg(0), Result, Info))
9223 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009224
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009225 if (Result.isNegative())
9226 Result.changeSign();
9227 return true;
9228
Richard Smith8889a3d2013-06-13 06:26:32 +00009229 // FIXME: Builtin::BI__builtin_powi
9230 // FIXME: Builtin::BI__builtin_powif
9231 // FIXME: Builtin::BI__builtin_powil
9232
Mike Stump11289f42009-09-09 15:08:12 +00009233 case Builtin::BI__builtin_copysign:
9234 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009235 case Builtin::BI__builtin_copysignl:
9236 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009237 APFloat RHS(0.);
9238 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9239 !EvaluateFloat(E->getArg(1), RHS, Info))
9240 return false;
9241 Result.copySign(RHS);
9242 return true;
9243 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009244 }
9245}
9246
John McCallb1fb0d32010-05-07 22:08:54 +00009247bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009248 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9249 ComplexValue CV;
9250 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9251 return false;
9252 Result = CV.FloatReal;
9253 return true;
9254 }
9255
9256 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009257}
9258
9259bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009260 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9261 ComplexValue CV;
9262 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9263 return false;
9264 Result = CV.FloatImag;
9265 return true;
9266 }
9267
Richard Smith4a678122011-10-24 18:44:57 +00009268 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009269 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9270 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009271 return true;
9272}
9273
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009274bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009275 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009276 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009277 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009278 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009279 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009280 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9281 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009282 Result.changeSign();
9283 return true;
9284 }
9285}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009286
Eli Friedman24c01542008-08-22 00:06:13 +00009287bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009288 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9289 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009290
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009291 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009292 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009293 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009294 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009295 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9296 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009297}
9298
9299bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9300 Result = E->getValue();
9301 return true;
9302}
9303
Peter Collingbournee9200682011-05-13 03:29:01 +00009304bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9305 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009306
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009307 switch (E->getCastKind()) {
9308 default:
Richard Smith11562c52011-10-28 17:51:58 +00009309 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009310
9311 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009312 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009313 return EvaluateInteger(SubExpr, IntResult, Info) &&
9314 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9315 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009316 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009317
9318 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009319 if (!Visit(SubExpr))
9320 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009321 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9322 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009323 }
John McCalld7646252010-11-14 08:17:51 +00009324
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009325 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009326 ComplexValue V;
9327 if (!EvaluateComplex(SubExpr, V, Info))
9328 return false;
9329 Result = V.getComplexFloatReal();
9330 return true;
9331 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009332 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009333}
9334
Eli Friedman24c01542008-08-22 00:06:13 +00009335//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009336// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009337//===----------------------------------------------------------------------===//
9338
9339namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009340class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009341 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009342 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009343
Anders Carlsson537969c2008-11-16 20:27:53 +00009344public:
John McCall93d91dc2010-05-07 17:22:02 +00009345 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009346 : ExprEvaluatorBaseTy(info), Result(Result) {}
9347
Richard Smith2e312c82012-03-03 22:46:17 +00009348 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009349 Result.setFrom(V);
9350 return true;
9351 }
Mike Stump11289f42009-09-09 15:08:12 +00009352
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009353 bool ZeroInitialization(const Expr *E);
9354
Anders Carlsson537969c2008-11-16 20:27:53 +00009355 //===--------------------------------------------------------------------===//
9356 // Visitor Methods
9357 //===--------------------------------------------------------------------===//
9358
Peter Collingbournee9200682011-05-13 03:29:01 +00009359 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009360 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009361 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009362 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009363 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009364};
9365} // end anonymous namespace
9366
John McCall93d91dc2010-05-07 17:22:02 +00009367static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9368 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009369 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009370 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009371}
9372
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009373bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009374 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009375 if (ElemTy->isRealFloatingType()) {
9376 Result.makeComplexFloat();
9377 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9378 Result.FloatReal = Zero;
9379 Result.FloatImag = Zero;
9380 } else {
9381 Result.makeComplexInt();
9382 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9383 Result.IntReal = Zero;
9384 Result.IntImag = Zero;
9385 }
9386 return true;
9387}
9388
Peter Collingbournee9200682011-05-13 03:29:01 +00009389bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9390 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009391
9392 if (SubExpr->getType()->isRealFloatingType()) {
9393 Result.makeComplexFloat();
9394 APFloat &Imag = Result.FloatImag;
9395 if (!EvaluateFloat(SubExpr, Imag, Info))
9396 return false;
9397
9398 Result.FloatReal = APFloat(Imag.getSemantics());
9399 return true;
9400 } else {
9401 assert(SubExpr->getType()->isIntegerType() &&
9402 "Unexpected imaginary literal.");
9403
9404 Result.makeComplexInt();
9405 APSInt &Imag = Result.IntImag;
9406 if (!EvaluateInteger(SubExpr, Imag, Info))
9407 return false;
9408
9409 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9410 return true;
9411 }
9412}
9413
Peter Collingbournee9200682011-05-13 03:29:01 +00009414bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009415
John McCallfcef3cf2010-12-14 17:51:41 +00009416 switch (E->getCastKind()) {
9417 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009418 case CK_BaseToDerived:
9419 case CK_DerivedToBase:
9420 case CK_UncheckedDerivedToBase:
9421 case CK_Dynamic:
9422 case CK_ToUnion:
9423 case CK_ArrayToPointerDecay:
9424 case CK_FunctionToPointerDecay:
9425 case CK_NullToPointer:
9426 case CK_NullToMemberPointer:
9427 case CK_BaseToDerivedMemberPointer:
9428 case CK_DerivedToBaseMemberPointer:
9429 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009430 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009431 case CK_ConstructorConversion:
9432 case CK_IntegralToPointer:
9433 case CK_PointerToIntegral:
9434 case CK_PointerToBoolean:
9435 case CK_ToVoid:
9436 case CK_VectorSplat:
9437 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009438 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009439 case CK_IntegralToBoolean:
9440 case CK_IntegralToFloating:
9441 case CK_FloatingToIntegral:
9442 case CK_FloatingToBoolean:
9443 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009444 case CK_CPointerToObjCPointerCast:
9445 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009446 case CK_AnyPointerToBlockPointerCast:
9447 case CK_ObjCObjectLValueCast:
9448 case CK_FloatingComplexToReal:
9449 case CK_FloatingComplexToBoolean:
9450 case CK_IntegralComplexToReal:
9451 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009452 case CK_ARCProduceObject:
9453 case CK_ARCConsumeObject:
9454 case CK_ARCReclaimReturnedObject:
9455 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009456 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009457 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009458 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009459 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009460 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009461 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009462 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009463 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009464
John McCallfcef3cf2010-12-14 17:51:41 +00009465 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009466 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009467 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009468 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009469
9470 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009471 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009472 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009473 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009474
9475 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009476 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009477 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009478 return false;
9479
John McCallfcef3cf2010-12-14 17:51:41 +00009480 Result.makeComplexFloat();
9481 Result.FloatImag = APFloat(Real.getSemantics());
9482 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009483 }
9484
John McCallfcef3cf2010-12-14 17:51:41 +00009485 case CK_FloatingComplexCast: {
9486 if (!Visit(E->getSubExpr()))
9487 return false;
9488
9489 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9490 QualType From
9491 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9492
Richard Smith357362d2011-12-13 06:39:58 +00009493 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9494 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009495 }
9496
9497 case CK_FloatingComplexToIntegralComplex: {
9498 if (!Visit(E->getSubExpr()))
9499 return false;
9500
9501 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9502 QualType From
9503 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9504 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009505 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9506 To, Result.IntReal) &&
9507 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9508 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009509 }
9510
9511 case CK_IntegralRealToComplex: {
9512 APSInt &Real = Result.IntReal;
9513 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9514 return false;
9515
9516 Result.makeComplexInt();
9517 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9518 return true;
9519 }
9520
9521 case CK_IntegralComplexCast: {
9522 if (!Visit(E->getSubExpr()))
9523 return false;
9524
9525 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9526 QualType From
9527 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9528
Richard Smith911e1422012-01-30 22:27:01 +00009529 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9530 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009531 return true;
9532 }
9533
9534 case CK_IntegralComplexToFloatingComplex: {
9535 if (!Visit(E->getSubExpr()))
9536 return false;
9537
Ted Kremenek28831752012-08-23 20:46:57 +00009538 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009539 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009540 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009541 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009542 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9543 To, Result.FloatReal) &&
9544 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9545 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009546 }
9547 }
9548
9549 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009550}
9551
John McCall93d91dc2010-05-07 17:22:02 +00009552bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009553 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009554 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9555
Chandler Carrutha216cad2014-10-11 00:57:18 +00009556 // Track whether the LHS or RHS is real at the type system level. When this is
9557 // the case we can simplify our evaluation strategy.
9558 bool LHSReal = false, RHSReal = false;
9559
9560 bool LHSOK;
9561 if (E->getLHS()->getType()->isRealFloatingType()) {
9562 LHSReal = true;
9563 APFloat &Real = Result.FloatReal;
9564 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9565 if (LHSOK) {
9566 Result.makeComplexFloat();
9567 Result.FloatImag = APFloat(Real.getSemantics());
9568 }
9569 } else {
9570 LHSOK = Visit(E->getLHS());
9571 }
George Burgess IVa145e252016-05-25 22:38:36 +00009572 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009573 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009574
John McCall93d91dc2010-05-07 17:22:02 +00009575 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009576 if (E->getRHS()->getType()->isRealFloatingType()) {
9577 RHSReal = true;
9578 APFloat &Real = RHS.FloatReal;
9579 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9580 return false;
9581 RHS.makeComplexFloat();
9582 RHS.FloatImag = APFloat(Real.getSemantics());
9583 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009584 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009585
Chandler Carrutha216cad2014-10-11 00:57:18 +00009586 assert(!(LHSReal && RHSReal) &&
9587 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009588 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009589 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009590 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009591 if (Result.isComplexFloat()) {
9592 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9593 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009594 if (LHSReal)
9595 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9596 else if (!RHSReal)
9597 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9598 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009599 } else {
9600 Result.getComplexIntReal() += RHS.getComplexIntReal();
9601 Result.getComplexIntImag() += RHS.getComplexIntImag();
9602 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009603 break;
John McCalle3027922010-08-25 11:45:40 +00009604 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009605 if (Result.isComplexFloat()) {
9606 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9607 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009608 if (LHSReal) {
9609 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9610 Result.getComplexFloatImag().changeSign();
9611 } else if (!RHSReal) {
9612 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9613 APFloat::rmNearestTiesToEven);
9614 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009615 } else {
9616 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9617 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9618 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009619 break;
John McCalle3027922010-08-25 11:45:40 +00009620 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009621 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009622 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009623 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009624 // following naming scheme:
9625 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009626 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009627 APFloat &A = LHS.getComplexFloatReal();
9628 APFloat &B = LHS.getComplexFloatImag();
9629 APFloat &C = RHS.getComplexFloatReal();
9630 APFloat &D = RHS.getComplexFloatImag();
9631 APFloat &ResR = Result.getComplexFloatReal();
9632 APFloat &ResI = Result.getComplexFloatImag();
9633 if (LHSReal) {
9634 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9635 ResR = A * C;
9636 ResI = A * D;
9637 } else if (RHSReal) {
9638 ResR = C * A;
9639 ResI = C * B;
9640 } else {
9641 // In the fully general case, we need to handle NaNs and infinities
9642 // robustly.
9643 APFloat AC = A * C;
9644 APFloat BD = B * D;
9645 APFloat AD = A * D;
9646 APFloat BC = B * C;
9647 ResR = AC - BD;
9648 ResI = AD + BC;
9649 if (ResR.isNaN() && ResI.isNaN()) {
9650 bool Recalc = false;
9651 if (A.isInfinity() || B.isInfinity()) {
9652 A = APFloat::copySign(
9653 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9654 B = APFloat::copySign(
9655 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9656 if (C.isNaN())
9657 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9658 if (D.isNaN())
9659 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9660 Recalc = true;
9661 }
9662 if (C.isInfinity() || D.isInfinity()) {
9663 C = APFloat::copySign(
9664 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9665 D = APFloat::copySign(
9666 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9667 if (A.isNaN())
9668 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9669 if (B.isNaN())
9670 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9671 Recalc = true;
9672 }
9673 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9674 AD.isInfinity() || BC.isInfinity())) {
9675 if (A.isNaN())
9676 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9677 if (B.isNaN())
9678 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9679 if (C.isNaN())
9680 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9681 if (D.isNaN())
9682 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9683 Recalc = true;
9684 }
9685 if (Recalc) {
9686 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9687 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9688 }
9689 }
9690 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009691 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009692 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009693 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009694 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9695 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009696 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009697 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9698 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9699 }
9700 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009701 case BO_Div:
9702 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009703 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009704 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009705 // following naming scheme:
9706 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009707 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009708 APFloat &A = LHS.getComplexFloatReal();
9709 APFloat &B = LHS.getComplexFloatImag();
9710 APFloat &C = RHS.getComplexFloatReal();
9711 APFloat &D = RHS.getComplexFloatImag();
9712 APFloat &ResR = Result.getComplexFloatReal();
9713 APFloat &ResI = Result.getComplexFloatImag();
9714 if (RHSReal) {
9715 ResR = A / C;
9716 ResI = B / C;
9717 } else {
9718 if (LHSReal) {
9719 // No real optimizations we can do here, stub out with zero.
9720 B = APFloat::getZero(A.getSemantics());
9721 }
9722 int DenomLogB = 0;
9723 APFloat MaxCD = maxnum(abs(C), abs(D));
9724 if (MaxCD.isFinite()) {
9725 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009726 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9727 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009728 }
9729 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009730 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9731 APFloat::rmNearestTiesToEven);
9732 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9733 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009734 if (ResR.isNaN() && ResI.isNaN()) {
9735 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9736 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9737 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9738 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9739 D.isFinite()) {
9740 A = APFloat::copySign(
9741 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9742 B = APFloat::copySign(
9743 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9744 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9745 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9746 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9747 C = APFloat::copySign(
9748 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9749 D = APFloat::copySign(
9750 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9751 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9752 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9753 }
9754 }
9755 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009756 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009757 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9758 return Error(E, diag::note_expr_divide_by_zero);
9759
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009760 ComplexValue LHS = Result;
9761 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9762 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9763 Result.getComplexIntReal() =
9764 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9765 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9766 Result.getComplexIntImag() =
9767 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9768 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9769 }
9770 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009771 }
9772
John McCall93d91dc2010-05-07 17:22:02 +00009773 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009774}
9775
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009776bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9777 // Get the operand value into 'Result'.
9778 if (!Visit(E->getSubExpr()))
9779 return false;
9780
9781 switch (E->getOpcode()) {
9782 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009783 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009784 case UO_Extension:
9785 return true;
9786 case UO_Plus:
9787 // The result is always just the subexpr.
9788 return true;
9789 case UO_Minus:
9790 if (Result.isComplexFloat()) {
9791 Result.getComplexFloatReal().changeSign();
9792 Result.getComplexFloatImag().changeSign();
9793 }
9794 else {
9795 Result.getComplexIntReal() = -Result.getComplexIntReal();
9796 Result.getComplexIntImag() = -Result.getComplexIntImag();
9797 }
9798 return true;
9799 case UO_Not:
9800 if (Result.isComplexFloat())
9801 Result.getComplexFloatImag().changeSign();
9802 else
9803 Result.getComplexIntImag() = -Result.getComplexIntImag();
9804 return true;
9805 }
9806}
9807
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009808bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9809 if (E->getNumInits() == 2) {
9810 if (E->getType()->isComplexType()) {
9811 Result.makeComplexFloat();
9812 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9813 return false;
9814 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9815 return false;
9816 } else {
9817 Result.makeComplexInt();
9818 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9819 return false;
9820 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9821 return false;
9822 }
9823 return true;
9824 }
9825 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9826}
9827
Anders Carlsson537969c2008-11-16 20:27:53 +00009828//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009829// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9830// implicit conversion.
9831//===----------------------------------------------------------------------===//
9832
9833namespace {
9834class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009835 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009836 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +00009837 APValue &Result;
9838public:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009839 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9840 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +00009841
9842 bool Success(const APValue &V, const Expr *E) {
9843 Result = V;
9844 return true;
9845 }
9846
9847 bool ZeroInitialization(const Expr *E) {
9848 ImplicitValueInitExpr VIE(
9849 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009850 // For atomic-qualified class (and array) types in C++, initialize the
9851 // _Atomic-wrapped subobject directly, in-place.
9852 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9853 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +00009854 }
9855
9856 bool VisitCastExpr(const CastExpr *E) {
9857 switch (E->getCastKind()) {
9858 default:
9859 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9860 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009861 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9862 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +00009863 }
9864 }
9865};
9866} // end anonymous namespace
9867
Richard Smith64cb9ca2017-02-22 22:09:50 +00009868static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9869 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +00009870 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009871 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +00009872}
9873
9874//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009875// Void expression evaluation, primarily for a cast to void on the LHS of a
9876// comma operator
9877//===----------------------------------------------------------------------===//
9878
9879namespace {
9880class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009881 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009882public:
9883 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9884
Richard Smith2e312c82012-03-03 22:46:17 +00009885 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009886
Richard Smith7cd577b2017-08-17 19:35:50 +00009887 bool ZeroInitialization(const Expr *E) { return true; }
9888
Richard Smith42d3af92011-12-07 00:43:50 +00009889 bool VisitCastExpr(const CastExpr *E) {
9890 switch (E->getCastKind()) {
9891 default:
9892 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9893 case CK_ToVoid:
9894 VisitIgnoredValue(E->getSubExpr());
9895 return true;
9896 }
9897 }
Hal Finkela8443c32014-07-17 14:49:58 +00009898
9899 bool VisitCallExpr(const CallExpr *E) {
9900 switch (E->getBuiltinCallee()) {
9901 default:
9902 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9903 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009904 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009905 // The argument is not evaluated!
9906 return true;
9907 }
9908 }
Richard Smith42d3af92011-12-07 00:43:50 +00009909};
9910} // end anonymous namespace
9911
9912static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9913 assert(E->isRValue() && E->getType()->isVoidType());
9914 return VoidExprEvaluator(Info).Visit(E);
9915}
9916
9917//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009918// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009919//===----------------------------------------------------------------------===//
9920
Richard Smith2e312c82012-03-03 22:46:17 +00009921static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009922 // In C, function designators are not lvalues, but we evaluate them as if they
9923 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009924 QualType T = E->getType();
9925 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009926 LValue LV;
9927 if (!EvaluateLValue(E, LV, Info))
9928 return false;
9929 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009930 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009931 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009932 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009933 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009934 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009935 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009936 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009937 LValue LV;
9938 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009939 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009940 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009941 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009942 llvm::APFloat F(0.0);
9943 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009944 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009945 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009946 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009947 ComplexValue C;
9948 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009949 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009950 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009951 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009952 MemberPtr P;
9953 if (!EvaluateMemberPointer(E, P, Info))
9954 return false;
9955 P.moveInto(Result);
9956 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009957 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009958 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009959 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009960 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9961 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009962 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009963 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009964 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009965 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009966 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009967 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9968 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009969 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009970 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009971 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009972 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009973 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009974 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009975 if (!EvaluateVoid(E, Info))
9976 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009977 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009978 QualType Unqual = T.getAtomicUnqualifiedType();
9979 if (Unqual->isArrayType() || Unqual->isRecordType()) {
9980 LValue LV;
9981 LV.set(E, Info.CurrentCall->Index);
9982 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9983 if (!EvaluateAtomic(E, &LV, Value, Info))
9984 return false;
9985 } else {
9986 if (!EvaluateAtomic(E, nullptr, Result, Info))
9987 return false;
9988 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009989 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009990 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009991 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009992 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009993 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009994 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009995 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009996
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009997 return true;
9998}
9999
Richard Smithb228a862012-02-15 02:18:13 +000010000/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10001/// cases, the in-place evaluation is essential, since later initializers for
10002/// an object can indirectly refer to subobjects which were initialized earlier.
10003static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000010004 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000010005 assert(!E->isValueDependent());
10006
Richard Smith7525ff62013-05-09 07:14:00 +000010007 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000010008 return false;
10009
10010 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000010011 // Evaluate arrays and record types in-place, so that later initializers can
10012 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000010013 QualType T = E->getType();
10014 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000010015 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010016 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000010017 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010018 else if (T->isAtomicType()) {
10019 QualType Unqual = T.getAtomicUnqualifiedType();
10020 if (Unqual->isArrayType() || Unqual->isRecordType())
10021 return EvaluateAtomic(E, &This, Result, Info);
10022 }
Richard Smithed5165f2011-11-04 05:33:44 +000010023 }
10024
10025 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010026 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010027}
10028
Richard Smithf57d8cb2011-12-09 22:58:01 +000010029/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10030/// lvalue-to-rvalue cast if it is an lvalue.
10031static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000010032 if (E->getType().isNull())
10033 return false;
10034
Nick Lewyckyc190f962017-05-02 01:06:16 +000010035 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000010036 return false;
10037
Richard Smith2e312c82012-03-03 22:46:17 +000010038 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010039 return false;
10040
10041 if (E->isGLValue()) {
10042 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000010043 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000010044 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010045 return false;
10046 }
10047
Richard Smith2e312c82012-03-03 22:46:17 +000010048 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000010049 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010050}
Richard Smith11562c52011-10-28 17:51:58 +000010051
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010052static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000010053 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010054 // Fast-path evaluations of integer literals, since we sometimes see files
10055 // containing vast quantities of these.
10056 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10057 Result.Val = APValue(APSInt(L->getValue(),
10058 L->getType()->isUnsignedIntegerType()));
10059 IsConst = true;
10060 return true;
10061 }
James Dennett0492ef02014-03-14 17:44:10 +000010062
10063 // This case should be rare, but we need to check it before we check on
10064 // the type below.
10065 if (Exp->getType().isNull()) {
10066 IsConst = false;
10067 return true;
10068 }
Daniel Jasperffdee092017-05-02 19:21:42 +000010069
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010070 // FIXME: Evaluating values of large array and record types can cause
10071 // performance problems. Only do so in C++11 for now.
10072 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10073 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010074 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010075 IsConst = false;
10076 return true;
10077 }
10078 return false;
10079}
10080
10081
Richard Smith7b553f12011-10-29 00:50:52 +000010082/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010083/// any crazy technique (that has nothing to do with language standards) that
10084/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010085/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10086/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +000010087bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010088 bool IsConst;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010089 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010090 return IsConst;
Daniel Jasperffdee092017-05-02 19:21:42 +000010091
Richard Smith6d4c6582013-11-05 22:18:15 +000010092 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010093 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +000010094}
10095
Jay Foad39c79802011-01-12 09:06:06 +000010096bool Expr::EvaluateAsBooleanCondition(bool &Result,
10097 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010098 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010099 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010100 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010101}
10102
Richard Smithce8eca52015-12-08 03:21:47 +000010103static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10104 Expr::SideEffectsKind SEK) {
10105 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10106 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10107}
10108
Richard Smith5fab0c92011-12-28 19:48:30 +000010109bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10110 SideEffectsKind AllowSideEffects) const {
10111 if (!getType()->isIntegralOrEnumerationType())
10112 return false;
10113
Richard Smith11562c52011-10-28 17:51:58 +000010114 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010115 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +000010116 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010117 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010118
Richard Smith11562c52011-10-28 17:51:58 +000010119 Result = ExprResult.Val.getInt();
10120 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010121}
10122
Richard Trieube234c32016-04-21 21:04:55 +000010123bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10124 SideEffectsKind AllowSideEffects) const {
10125 if (!getType()->isRealFloatingType())
10126 return false;
10127
10128 EvalResult ExprResult;
10129 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10130 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10131 return false;
10132
10133 Result = ExprResult.Val.getFloat();
10134 return true;
10135}
10136
Jay Foad39c79802011-01-12 09:06:06 +000010137bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010138 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010139
John McCall45d55e42010-05-07 21:00:08 +000010140 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010141 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10142 !CheckLValueConstantExpression(Info, getExprLoc(),
10143 Ctx.getLValueReferenceType(getType()), LV))
10144 return false;
10145
Richard Smith2e312c82012-03-03 22:46:17 +000010146 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010147 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010148}
10149
Richard Smithd0b4dd62011-12-19 06:19:21 +000010150bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10151 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010152 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010153 // FIXME: Evaluating initializers for large array and record types can cause
10154 // performance problems. Only do so in C++11 for now.
10155 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010156 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010157 return false;
10158
Richard Smithd0b4dd62011-12-19 06:19:21 +000010159 Expr::EvalStatus EStatus;
10160 EStatus.Diag = &Notes;
10161
Richard Smith0c6124b2015-12-03 01:36:22 +000010162 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10163 ? EvalInfo::EM_ConstantExpression
10164 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010165 InitInfo.setEvaluatingDecl(VD, Value);
10166
10167 LValue LVal;
10168 LVal.set(VD);
10169
Richard Smithfddd3842011-12-30 21:15:51 +000010170 // C++11 [basic.start.init]p2:
10171 // Variables with static storage duration or thread storage duration shall be
10172 // zero-initialized before any other initialization takes place.
10173 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010174 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010175 !VD->getType()->isReferenceType()) {
10176 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010177 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010178 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010179 return false;
10180 }
10181
Richard Smith7525ff62013-05-09 07:14:00 +000010182 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10183 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010184 EStatus.HasSideEffects)
10185 return false;
10186
10187 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10188 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010189}
10190
Richard Smith7b553f12011-10-29 00:50:52 +000010191/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10192/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010193bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010194 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010195 return EvaluateAsRValue(Result, Ctx) &&
10196 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010197}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010198
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010199APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010200 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010201 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010202 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010203 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010204 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010205 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010206 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010207
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010208 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010209}
John McCall864e3962010-05-07 05:32:02 +000010210
Richard Smithe9ff7702013-11-05 22:23:30 +000010211void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010212 bool IsConst;
10213 EvalResult EvalResult;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010214 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010215 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010216 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10217 }
10218}
10219
Richard Smithe6c01442013-06-05 00:46:14 +000010220bool Expr::EvalResult::isGlobalLValue() const {
10221 assert(Val.isLValue());
10222 return IsGlobalLValue(Val.getLValueBase());
10223}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010224
10225
John McCall864e3962010-05-07 05:32:02 +000010226/// isIntegerConstantExpr - this recursive routine will test if an expression is
10227/// an integer constant expression.
10228
10229/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10230/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010231
10232// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010233// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10234// and a (possibly null) SourceLocation indicating the location of the problem.
10235//
John McCall864e3962010-05-07 05:32:02 +000010236// Note that to reduce code duplication, this helper does no evaluation
10237// itself; the caller checks whether the expression is evaluatable, and
10238// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010239// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010240
Dan Gohman28ade552010-07-26 21:25:24 +000010241namespace {
10242
Richard Smith9e575da2012-12-28 13:25:52 +000010243enum ICEKind {
10244 /// This expression is an ICE.
10245 IK_ICE,
10246 /// This expression is not an ICE, but if it isn't evaluated, it's
10247 /// a legal subexpression for an ICE. This return value is used to handle
10248 /// the comma operator in C99 mode, and non-constant subexpressions.
10249 IK_ICEIfUnevaluated,
10250 /// This expression is not an ICE, and is not a legal subexpression for one.
10251 IK_NotICE
10252};
10253
John McCall864e3962010-05-07 05:32:02 +000010254struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010255 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010256 SourceLocation Loc;
10257
Richard Smith9e575da2012-12-28 13:25:52 +000010258 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010259};
10260
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010261}
Dan Gohman28ade552010-07-26 21:25:24 +000010262
Richard Smith9e575da2012-12-28 13:25:52 +000010263static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10264
10265static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010266
Craig Toppera31a8822013-08-22 07:09:37 +000010267static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010268 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010269 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010270 !EVResult.Val.isInt())
10271 return ICEDiag(IK_NotICE, E->getLocStart());
10272
John McCall864e3962010-05-07 05:32:02 +000010273 return NoDiag();
10274}
10275
Craig Toppera31a8822013-08-22 07:09:37 +000010276static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010277 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010278 if (!E->getType()->isIntegralOrEnumerationType())
10279 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010280
10281 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010282#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010283#define STMT(Node, Base) case Expr::Node##Class:
10284#define EXPR(Node, Base)
10285#include "clang/AST/StmtNodes.inc"
10286 case Expr::PredefinedExprClass:
10287 case Expr::FloatingLiteralClass:
10288 case Expr::ImaginaryLiteralClass:
10289 case Expr::StringLiteralClass:
10290 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010291 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010292 case Expr::MemberExprClass:
10293 case Expr::CompoundAssignOperatorClass:
10294 case Expr::CompoundLiteralExprClass:
10295 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010296 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010297 case Expr::ArrayInitLoopExprClass:
10298 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010299 case Expr::NoInitExprClass:
10300 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010301 case Expr::ImplicitValueInitExprClass:
10302 case Expr::ParenListExprClass:
10303 case Expr::VAArgExprClass:
10304 case Expr::AddrLabelExprClass:
10305 case Expr::StmtExprClass:
10306 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010307 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010308 case Expr::CXXDynamicCastExprClass:
10309 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010310 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010311 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010312 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010313 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010314 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010315 case Expr::CXXThisExprClass:
10316 case Expr::CXXThrowExprClass:
10317 case Expr::CXXNewExprClass:
10318 case Expr::CXXDeleteExprClass:
10319 case Expr::CXXPseudoDestructorExprClass:
10320 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010321 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010322 case Expr::DependentScopeDeclRefExprClass:
10323 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010324 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010325 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010326 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010327 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010328 case Expr::CXXTemporaryObjectExprClass:
10329 case Expr::CXXUnresolvedConstructExprClass:
10330 case Expr::CXXDependentScopeMemberExprClass:
10331 case Expr::UnresolvedMemberExprClass:
10332 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010333 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010334 case Expr::ObjCArrayLiteralClass:
10335 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010336 case Expr::ObjCEncodeExprClass:
10337 case Expr::ObjCMessageExprClass:
10338 case Expr::ObjCSelectorExprClass:
10339 case Expr::ObjCProtocolExprClass:
10340 case Expr::ObjCIvarRefExprClass:
10341 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010342 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010343 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010344 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010345 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010346 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010347 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010348 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010349 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010350 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010351 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010352 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010353 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010354 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010355 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010356 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010357 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010358 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010359 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010360 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000010361 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010362 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010363 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010364
Richard Smithf137f932014-01-25 20:50:08 +000010365 case Expr::InitListExprClass: {
10366 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10367 // form "T x = { a };" is equivalent to "T x = a;".
10368 // Unless we're initializing a reference, T is a scalar as it is known to be
10369 // of integral or enumeration type.
10370 if (E->isRValue())
10371 if (cast<InitListExpr>(E)->getNumInits() == 1)
10372 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10373 return ICEDiag(IK_NotICE, E->getLocStart());
10374 }
10375
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010376 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010377 case Expr::GNUNullExprClass:
10378 // GCC considers the GNU __null value to be an integral constant expression.
10379 return NoDiag();
10380
John McCall7c454bb2011-07-15 05:09:51 +000010381 case Expr::SubstNonTypeTemplateParmExprClass:
10382 return
10383 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10384
John McCall864e3962010-05-07 05:32:02 +000010385 case Expr::ParenExprClass:
10386 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010387 case Expr::GenericSelectionExprClass:
10388 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010389 case Expr::IntegerLiteralClass:
10390 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010391 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010392 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010393 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010394 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010395 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010396 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010397 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010398 return NoDiag();
10399 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010400 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010401 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10402 // constant expressions, but they can never be ICEs because an ICE cannot
10403 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010404 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010405 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010406 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010407 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010408 }
Richard Smith6365c912012-02-24 22:12:32 +000010409 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010410 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10411 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010412 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010413 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010414 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010415 // Parameter variables are never constants. Without this check,
10416 // getAnyInitializer() can find a default argument, which leads
10417 // to chaos.
10418 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010419 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010420
10421 // C++ 7.1.5.1p2
10422 // A variable of non-volatile const-qualified integral or enumeration
10423 // type initialized by an ICE can be used in ICEs.
10424 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010425 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010426 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010427
Richard Smithd0b4dd62011-12-19 06:19:21 +000010428 const VarDecl *VD;
10429 // Look for a declaration of this variable that has an initializer, and
10430 // check whether it is an ICE.
10431 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10432 return NoDiag();
10433 else
Richard Smith9e575da2012-12-28 13:25:52 +000010434 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010435 }
10436 }
Richard Smith9e575da2012-12-28 13:25:52 +000010437 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010438 }
John McCall864e3962010-05-07 05:32:02 +000010439 case Expr::UnaryOperatorClass: {
10440 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10441 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010442 case UO_PostInc:
10443 case UO_PostDec:
10444 case UO_PreInc:
10445 case UO_PreDec:
10446 case UO_AddrOf:
10447 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010448 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010449 // C99 6.6/3 allows increment and decrement within unevaluated
10450 // subexpressions of constant expressions, but they can never be ICEs
10451 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010452 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010453 case UO_Extension:
10454 case UO_LNot:
10455 case UO_Plus:
10456 case UO_Minus:
10457 case UO_Not:
10458 case UO_Real:
10459 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010460 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010461 }
Richard Smith9e575da2012-12-28 13:25:52 +000010462
John McCall864e3962010-05-07 05:32:02 +000010463 // OffsetOf falls through here.
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010464 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010465 }
10466 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010467 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10468 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10469 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10470 // compliance: we should warn earlier for offsetof expressions with
10471 // array subscripts that aren't ICEs, and if the array subscripts
10472 // are ICEs, the value of the offsetof must be an integer constant.
10473 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010474 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010475 case Expr::UnaryExprOrTypeTraitExprClass: {
10476 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10477 if ((Exp->getKind() == UETT_SizeOf) &&
10478 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010479 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010480 return NoDiag();
10481 }
10482 case Expr::BinaryOperatorClass: {
10483 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10484 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010485 case BO_PtrMemD:
10486 case BO_PtrMemI:
10487 case BO_Assign:
10488 case BO_MulAssign:
10489 case BO_DivAssign:
10490 case BO_RemAssign:
10491 case BO_AddAssign:
10492 case BO_SubAssign:
10493 case BO_ShlAssign:
10494 case BO_ShrAssign:
10495 case BO_AndAssign:
10496 case BO_XorAssign:
10497 case BO_OrAssign:
Richard Smithc70f1d62017-12-14 15:16:18 +000010498 case BO_Cmp: // FIXME: Re-enable once we can evaluate this.
Richard Smith62f65952011-10-24 22:35:48 +000010499 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10500 // constant expressions, but they can never be ICEs because an ICE cannot
10501 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010502 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010503
John McCalle3027922010-08-25 11:45:40 +000010504 case BO_Mul:
10505 case BO_Div:
10506 case BO_Rem:
10507 case BO_Add:
10508 case BO_Sub:
10509 case BO_Shl:
10510 case BO_Shr:
10511 case BO_LT:
10512 case BO_GT:
10513 case BO_LE:
10514 case BO_GE:
10515 case BO_EQ:
10516 case BO_NE:
10517 case BO_And:
10518 case BO_Xor:
10519 case BO_Or:
10520 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010521 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10522 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010523 if (Exp->getOpcode() == BO_Div ||
10524 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010525 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010526 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010527 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010528 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010529 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010530 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010531 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010532 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010533 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010534 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010535 }
10536 }
10537 }
John McCalle3027922010-08-25 11:45:40 +000010538 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010539 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010540 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10541 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010542 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10543 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010544 } else {
10545 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010546 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010547 }
10548 }
Richard Smith9e575da2012-12-28 13:25:52 +000010549 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010550 }
John McCalle3027922010-08-25 11:45:40 +000010551 case BO_LAnd:
10552 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010553 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10554 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010555 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010556 // Rare case where the RHS has a comma "side-effect"; we need
10557 // to actually check the condition to see whether the side
10558 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010559 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010560 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010561 return RHSResult;
10562 return NoDiag();
10563 }
10564
Richard Smith9e575da2012-12-28 13:25:52 +000010565 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010566 }
10567 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010568 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010569 }
10570 case Expr::ImplicitCastExprClass:
10571 case Expr::CStyleCastExprClass:
10572 case Expr::CXXFunctionalCastExprClass:
10573 case Expr::CXXStaticCastExprClass:
10574 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010575 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010576 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010577 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010578 if (isa<ExplicitCastExpr>(E)) {
10579 if (const FloatingLiteral *FL
10580 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10581 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10582 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10583 APSInt IgnoredVal(DestWidth, !DestSigned);
10584 bool Ignored;
10585 // If the value does not fit in the destination type, the behavior is
10586 // undefined, so we are not required to treat it as a constant
10587 // expression.
10588 if (FL->getValue().convertToInteger(IgnoredVal,
10589 llvm::APFloat::rmTowardZero,
10590 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010591 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010592 return NoDiag();
10593 }
10594 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010595 switch (cast<CastExpr>(E)->getCastKind()) {
10596 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010597 case CK_AtomicToNonAtomic:
10598 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010599 case CK_NoOp:
10600 case CK_IntegralToBoolean:
10601 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010602 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010603 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010604 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010605 }
John McCall864e3962010-05-07 05:32:02 +000010606 }
John McCallc07a0c72011-02-17 10:25:35 +000010607 case Expr::BinaryConditionalOperatorClass: {
10608 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10609 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010610 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010611 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010612 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10613 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10614 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010615 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010616 return FalseResult;
10617 }
John McCall864e3962010-05-07 05:32:02 +000010618 case Expr::ConditionalOperatorClass: {
10619 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10620 // If the condition (ignoring parens) is a __builtin_constant_p call,
10621 // then only the true side is actually considered in an integer constant
10622 // expression, and it is fully evaluated. This is an important GNU
10623 // extension. See GCC PR38377 for discussion.
10624 if (const CallExpr *CallCE
10625 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010626 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010627 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010628 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010629 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010630 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010631
Richard Smithf57d8cb2011-12-09 22:58:01 +000010632 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10633 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010634
Richard Smith9e575da2012-12-28 13:25:52 +000010635 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010636 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010637 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010638 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010639 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010640 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010641 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010642 return NoDiag();
10643 // Rare case where the diagnostics depend on which side is evaluated
10644 // Note that if we get here, CondResult is 0, and at least one of
10645 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010646 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010647 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010648 return TrueResult;
10649 }
10650 case Expr::CXXDefaultArgExprClass:
10651 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010652 case Expr::CXXDefaultInitExprClass:
10653 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010654 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010655 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010656 }
10657 }
10658
David Blaikiee4d798f2012-01-20 21:50:17 +000010659 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010660}
10661
Richard Smithf57d8cb2011-12-09 22:58:01 +000010662/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010663static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010664 const Expr *E,
10665 llvm::APSInt *Value,
10666 SourceLocation *Loc) {
10667 if (!E->getType()->isIntegralOrEnumerationType()) {
10668 if (Loc) *Loc = E->getExprLoc();
10669 return false;
10670 }
10671
Richard Smith66e05fe2012-01-18 05:21:49 +000010672 APValue Result;
10673 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010674 return false;
10675
Richard Smith98710fc2014-11-13 23:03:19 +000010676 if (!Result.isInt()) {
10677 if (Loc) *Loc = E->getExprLoc();
10678 return false;
10679 }
10680
Richard Smith66e05fe2012-01-18 05:21:49 +000010681 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010682 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010683}
10684
Craig Toppera31a8822013-08-22 07:09:37 +000010685bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10686 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010687 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010688 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010689
Richard Smith9e575da2012-12-28 13:25:52 +000010690 ICEDiag D = CheckICE(this, Ctx);
10691 if (D.Kind != IK_ICE) {
10692 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010693 return false;
10694 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010695 return true;
10696}
10697
Craig Toppera31a8822013-08-22 07:09:37 +000010698bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010699 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010700 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010701 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10702
10703 if (!isIntegerConstantExpr(Ctx, Loc))
10704 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010705 // The only possible side-effects here are due to UB discovered in the
10706 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10707 // required to treat the expression as an ICE, so we produce the folded
10708 // value.
10709 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010710 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010711 return true;
10712}
Richard Smith66e05fe2012-01-18 05:21:49 +000010713
Craig Toppera31a8822013-08-22 07:09:37 +000010714bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010715 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010716}
10717
Craig Toppera31a8822013-08-22 07:09:37 +000010718bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010719 SourceLocation *Loc) const {
10720 // We support this checking in C++98 mode in order to diagnose compatibility
10721 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010722 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010723
Richard Smith98a0a492012-02-14 21:38:30 +000010724 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010725 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010726 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010727 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010728 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010729
10730 APValue Scratch;
10731 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10732
10733 if (!Diags.empty()) {
10734 IsConstExpr = false;
10735 if (Loc) *Loc = Diags[0].first;
10736 } else if (!IsConstExpr) {
10737 // FIXME: This shouldn't happen.
10738 if (Loc) *Loc = getExprLoc();
10739 }
10740
10741 return IsConstExpr;
10742}
Richard Smith253c2a32012-01-27 01:14:48 +000010743
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010744bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10745 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010746 ArrayRef<const Expr*> Args,
10747 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010748 Expr::EvalStatus Status;
10749 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10750
George Burgess IV177399e2017-01-09 04:12:14 +000010751 LValue ThisVal;
10752 const LValue *ThisPtr = nullptr;
10753 if (This) {
10754#ifndef NDEBUG
10755 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10756 assert(MD && "Don't provide `this` for non-methods.");
10757 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10758#endif
10759 if (EvaluateObjectArgument(Info, This, ThisVal))
10760 ThisPtr = &ThisVal;
10761 if (Info.EvalStatus.HasSideEffects)
10762 return false;
10763 }
10764
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010765 ArgVector ArgValues(Args.size());
10766 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10767 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010768 if ((*I)->isValueDependent() ||
10769 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010770 // If evaluation fails, throw away the argument entirely.
10771 ArgValues[I - Args.begin()] = APValue();
10772 if (Info.EvalStatus.HasSideEffects)
10773 return false;
10774 }
10775
10776 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010777 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010778 ArgValues.data());
10779 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10780}
10781
Richard Smith253c2a32012-01-27 01:14:48 +000010782bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010783 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010784 PartialDiagnosticAt> &Diags) {
10785 // FIXME: It would be useful to check constexpr function templates, but at the
10786 // moment the constant expression evaluator cannot cope with the non-rigorous
10787 // ASTs which we build for dependent expressions.
10788 if (FD->isDependentContext())
10789 return true;
10790
10791 Expr::EvalStatus Status;
10792 Status.Diag = &Diags;
10793
Richard Smith6d4c6582013-11-05 22:18:15 +000010794 EvalInfo Info(FD->getASTContext(), Status,
10795 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010796
10797 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010798 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010799
Richard Smith7525ff62013-05-09 07:14:00 +000010800 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010801 // is a temporary being used as the 'this' pointer.
10802 LValue This;
10803 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010804 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010805
Richard Smith253c2a32012-01-27 01:14:48 +000010806 ArrayRef<const Expr*> Args;
10807
Richard Smith2e312c82012-03-03 22:46:17 +000010808 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010809 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10810 // Evaluate the call as a constant initializer, to allow the construction
10811 // of objects of non-literal types.
10812 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010813 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10814 } else {
10815 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010816 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010817 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010818 }
Richard Smith253c2a32012-01-27 01:14:48 +000010819
10820 return Diags.empty();
10821}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010822
10823bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10824 const FunctionDecl *FD,
10825 SmallVectorImpl<
10826 PartialDiagnosticAt> &Diags) {
10827 Expr::EvalStatus Status;
10828 Status.Diag = &Diags;
10829
10830 EvalInfo Info(FD->getASTContext(), Status,
10831 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10832
10833 // Fabricate a call stack frame to give the arguments a plausible cover story.
10834 ArrayRef<const Expr*> Args;
10835 ArgVector ArgValues(0);
10836 bool Success = EvaluateArgs(Args, ArgValues, Info);
10837 (void)Success;
10838 assert(Success &&
10839 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010840 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010841
10842 APValue ResultScratch;
10843 Evaluate(ResultScratch, Info, E);
10844 return Diags.empty();
10845}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010846
10847bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10848 unsigned Type) const {
10849 if (!getType()->isPointerType())
10850 return false;
10851
10852 Expr::EvalStatus Status;
10853 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010854 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010855}