blob: 6ef6d566665a6eff1bdabc5a18721909b82c0e0a [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;
Richard Smith9defb7d2018-02-21 03:38:30 +00002649 bool LifetimeStartedInEvaluation;
Richard Smith3229b742013-05-05 21:17:10 +00002650
Craig Topper36250ad2014-05-12 05:36:57 +00002651 CompleteObject() : Value(nullptr) {}
Richard Smith9defb7d2018-02-21 03:38:30 +00002652 CompleteObject(APValue *Value, QualType Type,
2653 bool LifetimeStartedInEvaluation)
2654 : Value(Value), Type(Type),
2655 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
Richard Smith3229b742013-05-05 21:17:10 +00002656 assert(Value && "missing value for complete object");
2657 }
2658
Aaron Ballman67347662015-02-15 22:00:28 +00002659 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002660};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002661} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002662
Richard Smith3da88fa2013-04-26 14:36:30 +00002663/// Find the designated sub-object of an rvalue.
2664template<typename SubobjectHandler>
2665typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002666findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002667 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002668 if (Sub.Invalid)
2669 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002670 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002671 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002672 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002673 Info.FFDiag(E, Sub.isOnePastTheEnd()
2674 ? diag::note_constexpr_access_past_end
2675 : diag::note_constexpr_access_unsized_array)
2676 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002677 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002678 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002679 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002680 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002681
Richard Smith3229b742013-05-05 21:17:10 +00002682 APValue *O = Obj.Value;
2683 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002684 const FieldDecl *LastField = nullptr;
Richard Smith9defb7d2018-02-21 03:38:30 +00002685 const bool MayReadMutableMembers =
2686 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002687
Richard Smithd62306a2011-11-10 06:34:14 +00002688 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002689 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2690 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002691 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002692 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002693 return handler.failed();
2694 }
2695
Richard Smith49ca8aa2013-08-06 07:09:20 +00002696 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002697 // If we are reading an object of class type, there may still be more
2698 // things we need to check: if there are any mutable subobjects, we
2699 // cannot perform this read. (This only happens when performing a trivial
2700 // copy or assignment.)
2701 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smith9defb7d2018-02-21 03:38:30 +00002702 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002703 return handler.failed();
2704
Richard Smith49ca8aa2013-08-06 07:09:20 +00002705 if (!handler.found(*O, ObjType))
2706 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002707
Richard Smith49ca8aa2013-08-06 07:09:20 +00002708 // If we modified a bit-field, truncate it to the right width.
2709 if (handler.AccessKind != AK_Read &&
2710 LastField && LastField->isBitField() &&
2711 !truncateBitfieldValue(Info, E, *O, LastField))
2712 return false;
2713
2714 return true;
2715 }
2716
Craig Topper36250ad2014-05-12 05:36:57 +00002717 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002718 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002719 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002720 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002721 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002722 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002723 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002724 // Note, it should not be possible to form a pointer with a valid
2725 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002726 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002727 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002728 << handler.AccessKind;
2729 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002730 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002731 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002732 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002733
2734 ObjType = CAT->getElementType();
2735
Richard Smith14a94132012-02-17 03:35:37 +00002736 // An array object is represented as either an Array APValue or as an
2737 // LValue which refers to a string literal.
2738 if (O->isLValue()) {
2739 assert(I == N - 1 && "extracting subobject of character?");
2740 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002741 if (handler.AccessKind != AK_Read)
2742 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2743 *O);
2744 else
2745 return handler.foundString(*O, ObjType, Index);
2746 }
2747
2748 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002749 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002750 else if (handler.AccessKind != AK_Read) {
2751 expandArray(*O, Index);
2752 O = &O->getArrayInitializedElt(Index);
2753 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002754 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002755 } else if (ObjType->isAnyComplexType()) {
2756 // Next subobject is a complex number.
2757 uint64_t Index = Sub.Entries[I].ArrayIndex;
2758 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002759 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002760 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002761 << handler.AccessKind;
2762 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002763 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002764 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002765 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002766
2767 bool WasConstQualified = ObjType.isConstQualified();
2768 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2769 if (WasConstQualified)
2770 ObjType.addConst();
2771
Richard Smith66c96992012-02-18 22:04:06 +00002772 assert(I == N - 1 && "extracting subobject of scalar?");
2773 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002774 return handler.found(Index ? O->getComplexIntImag()
2775 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002776 } else {
2777 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002778 return handler.found(Index ? O->getComplexFloatImag()
2779 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002780 }
Richard Smithd62306a2011-11-10 06:34:14 +00002781 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00002782 // In C++14 onwards, it is permitted to read a mutable member whose
2783 // lifetime began within the evaluation.
2784 // FIXME: Should we also allow this in C++11?
2785 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2786 !MayReadMutableMembers) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002787 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002788 << Field;
2789 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002790 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002791 }
2792
Richard Smithd62306a2011-11-10 06:34:14 +00002793 // Next subobject is a class, struct or union field.
2794 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2795 if (RD->isUnion()) {
2796 const FieldDecl *UnionField = O->getUnionField();
2797 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002798 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002799 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002800 << handler.AccessKind << Field << !UnionField << UnionField;
2801 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002802 }
Richard Smithd62306a2011-11-10 06:34:14 +00002803 O = &O->getUnionValue();
2804 } else
2805 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002806
2807 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002808 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002809 if (WasConstQualified && !Field->isMutable())
2810 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002811
2812 if (ObjType.isVolatileQualified()) {
2813 if (Info.getLangOpts().CPlusPlus) {
2814 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002815 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002816 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002817 Info.Note(Field->getLocation(), diag::note_declared_at);
2818 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002819 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002820 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002821 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002822 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002823
2824 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002825 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002826 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002827 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2828 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2829 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002830
2831 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002832 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002833 if (WasConstQualified)
2834 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002835 }
2836 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002837}
2838
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002839namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002840struct ExtractSubobjectHandler {
2841 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002842 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002843
2844 static const AccessKinds AccessKind = AK_Read;
2845
2846 typedef bool result_type;
2847 bool failed() { return false; }
2848 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002849 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002850 return true;
2851 }
2852 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002853 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002854 return true;
2855 }
2856 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002857 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002858 return true;
2859 }
2860 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002861 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002862 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2863 return true;
2864 }
2865};
Richard Smith3229b742013-05-05 21:17:10 +00002866} // end anonymous namespace
2867
Richard Smith3da88fa2013-04-26 14:36:30 +00002868const AccessKinds ExtractSubobjectHandler::AccessKind;
2869
2870/// Extract the designated sub-object of an rvalue.
2871static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002872 const CompleteObject &Obj,
2873 const SubobjectDesignator &Sub,
2874 APValue &Result) {
2875 ExtractSubobjectHandler Handler = { Info, Result };
2876 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002877}
2878
Richard Smith3229b742013-05-05 21:17:10 +00002879namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002880struct ModifySubobjectHandler {
2881 EvalInfo &Info;
2882 APValue &NewVal;
2883 const Expr *E;
2884
2885 typedef bool result_type;
2886 static const AccessKinds AccessKind = AK_Assign;
2887
2888 bool checkConst(QualType QT) {
2889 // Assigning to a const object has undefined behavior.
2890 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002891 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002892 return false;
2893 }
2894 return true;
2895 }
2896
2897 bool failed() { return false; }
2898 bool found(APValue &Subobj, QualType SubobjType) {
2899 if (!checkConst(SubobjType))
2900 return false;
2901 // We've been given ownership of NewVal, so just swap it in.
2902 Subobj.swap(NewVal);
2903 return true;
2904 }
2905 bool found(APSInt &Value, QualType SubobjType) {
2906 if (!checkConst(SubobjType))
2907 return false;
2908 if (!NewVal.isInt()) {
2909 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002910 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002911 return false;
2912 }
2913 Value = NewVal.getInt();
2914 return true;
2915 }
2916 bool found(APFloat &Value, QualType SubobjType) {
2917 if (!checkConst(SubobjType))
2918 return false;
2919 Value = NewVal.getFloat();
2920 return true;
2921 }
2922 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2923 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2924 }
2925};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002926} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002927
Richard Smith3229b742013-05-05 21:17:10 +00002928const AccessKinds ModifySubobjectHandler::AccessKind;
2929
Richard Smith3da88fa2013-04-26 14:36:30 +00002930/// Update the designated sub-object of an rvalue to the given value.
2931static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002932 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002933 const SubobjectDesignator &Sub,
2934 APValue &NewVal) {
2935 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002936 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002937}
2938
Richard Smith84f6dcf2012-02-02 01:16:57 +00002939/// Find the position where two subobject designators diverge, or equivalently
2940/// the length of the common initial subsequence.
2941static unsigned FindDesignatorMismatch(QualType ObjType,
2942 const SubobjectDesignator &A,
2943 const SubobjectDesignator &B,
2944 bool &WasArrayIndex) {
2945 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2946 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002947 if (!ObjType.isNull() &&
2948 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002949 // Next subobject is an array element.
2950 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2951 WasArrayIndex = true;
2952 return I;
2953 }
Richard Smith66c96992012-02-18 22:04:06 +00002954 if (ObjType->isAnyComplexType())
2955 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2956 else
2957 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002958 } else {
2959 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2960 WasArrayIndex = false;
2961 return I;
2962 }
2963 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2964 // Next subobject is a field.
2965 ObjType = FD->getType();
2966 else
2967 // Next subobject is a base class.
2968 ObjType = QualType();
2969 }
2970 }
2971 WasArrayIndex = false;
2972 return I;
2973}
2974
2975/// Determine whether the given subobject designators refer to elements of the
2976/// same array object.
2977static bool AreElementsOfSameArray(QualType ObjType,
2978 const SubobjectDesignator &A,
2979 const SubobjectDesignator &B) {
2980 if (A.Entries.size() != B.Entries.size())
2981 return false;
2982
George Burgess IVa51c4072015-10-16 01:49:01 +00002983 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002984 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2985 // A is a subobject of the array element.
2986 return false;
2987
2988 // If A (and B) designates an array element, the last entry will be the array
2989 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2990 // of length 1' case, and the entire path must match.
2991 bool WasArrayIndex;
2992 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2993 return CommonLength >= A.Entries.size() - IsArray;
2994}
2995
Richard Smith3229b742013-05-05 21:17:10 +00002996/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002997static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2998 AccessKinds AK, const LValue &LVal,
2999 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00003000 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003001 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003002 return CompleteObject();
3003 }
3004
Craig Topper36250ad2014-05-12 05:36:57 +00003005 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00003006 if (LVal.CallIndex) {
3007 Frame = Info.getCallFrame(LVal.CallIndex);
3008 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003009 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003010 << AK << LVal.Base.is<const ValueDecl*>();
3011 NoteLValueLocation(Info, LVal.Base);
3012 return CompleteObject();
3013 }
Richard Smith3229b742013-05-05 21:17:10 +00003014 }
3015
3016 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3017 // is not a constant expression (even if the object is non-volatile). We also
3018 // apply this rule to C++98, in order to conform to the expected 'volatile'
3019 // semantics.
3020 if (LValType.isVolatileQualified()) {
3021 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003022 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003023 << AK << LValType;
3024 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003025 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003026 return CompleteObject();
3027 }
3028
3029 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003030 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003031 QualType BaseType = getType(LVal.Base);
Richard Smith9defb7d2018-02-21 03:38:30 +00003032 bool LifetimeStartedInEvaluation = Frame;
Richard Smith3229b742013-05-05 21:17:10 +00003033
3034 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3035 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3036 // In C++11, constexpr, non-volatile variables initialized with constant
3037 // expressions are constant expressions too. Inside constexpr functions,
3038 // parameters are constant expressions even if they're non-const.
3039 // In C++1y, objects local to a constant expression (those with a Frame) are
3040 // both readable and writable inside constant expressions.
3041 // In C, such things can also be folded, although they are not ICEs.
3042 const VarDecl *VD = dyn_cast<VarDecl>(D);
3043 if (VD) {
3044 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3045 VD = VDef;
3046 }
3047 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003048 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003049 return CompleteObject();
3050 }
3051
3052 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003053 if (BaseType.isVolatileQualified()) {
3054 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003055 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003056 << AK << 1 << VD;
3057 Info.Note(VD->getLocation(), diag::note_declared_at);
3058 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003059 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003060 }
3061 return CompleteObject();
3062 }
3063
3064 // Unless we're looking at a local variable or argument in a constexpr call,
3065 // the variable we're reading must be const.
3066 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003067 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003068 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3069 // OK, we can read and modify an object if we're in the process of
3070 // evaluating its initializer, because its lifetime began in this
3071 // evaluation.
3072 } else if (AK != AK_Read) {
3073 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003074 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003075 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003076 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003077 // OK, we can read this variable.
3078 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003079 // In OpenCL if a variable is in constant address space it is a const value.
3080 if (!(BaseType.isConstQualified() ||
3081 (Info.getLangOpts().OpenCL &&
3082 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003083 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003084 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003085 Info.Note(VD->getLocation(), diag::note_declared_at);
3086 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003087 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003088 }
3089 return CompleteObject();
3090 }
3091 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3092 // We support folding of const floating-point types, in order to make
3093 // static const data members of such types (supported as an extension)
3094 // more useful.
3095 if (Info.getLangOpts().CPlusPlus11) {
3096 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3097 Info.Note(VD->getLocation(), diag::note_declared_at);
3098 } else {
3099 Info.CCEDiag(E);
3100 }
George Burgess IVb5316982016-12-27 05:33:20 +00003101 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3102 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3103 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003104 } else {
3105 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003106 if (Info.checkingPotentialConstantExpression() &&
3107 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3108 // The definition of this variable could be constexpr. We can't
3109 // access it right now, but may be able to in future.
3110 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003111 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003112 Info.Note(VD->getLocation(), diag::note_declared_at);
3113 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003114 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003115 }
3116 return CompleteObject();
3117 }
3118 }
3119
3120 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3121 return CompleteObject();
3122 } else {
3123 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3124
3125 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003126 if (const MaterializeTemporaryExpr *MTE =
3127 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3128 assert(MTE->getStorageDuration() == SD_Static &&
3129 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003130
Richard Smithe6c01442013-06-05 00:46:14 +00003131 // Per C++1y [expr.const]p2:
3132 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3133 // - a [...] glvalue of integral or enumeration type that refers to
3134 // a non-volatile const object [...]
3135 // [...]
3136 // - a [...] glvalue of literal type that refers to a non-volatile
3137 // object whose lifetime began within the evaluation of e.
3138 //
3139 // C++11 misses the 'began within the evaluation of e' check and
3140 // instead allows all temporaries, including things like:
3141 // int &&r = 1;
3142 // int x = ++r;
3143 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003144 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003145 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3146 const ValueDecl *ED = MTE->getExtendingDecl();
3147 if (!(BaseType.isConstQualified() &&
3148 BaseType->isIntegralOrEnumerationType()) &&
3149 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003150 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003151 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3152 return CompleteObject();
3153 }
3154
3155 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3156 assert(BaseVal && "got reference to unevaluated temporary");
Richard Smith9defb7d2018-02-21 03:38:30 +00003157 LifetimeStartedInEvaluation = true;
Richard Smithe6c01442013-06-05 00:46:14 +00003158 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003159 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003160 return CompleteObject();
3161 }
3162 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003163 BaseVal = Frame->getTemporary(Base);
3164 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003165 }
Richard Smith3229b742013-05-05 21:17:10 +00003166
3167 // Volatile temporary objects cannot be accessed in constant expressions.
3168 if (BaseType.isVolatileQualified()) {
3169 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003170 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003171 << AK << 0;
3172 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3173 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003174 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003175 }
3176 return CompleteObject();
3177 }
3178 }
3179
Richard Smith7525ff62013-05-09 07:14:00 +00003180 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003181 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003182 // object under construction.
Erik Pilkington42925492017-10-04 00:18:55 +00003183 if (Info.isEvaluatingConstructor(LVal.getLValueBase(), LVal.CallIndex)) {
Richard Smith7525ff62013-05-09 07:14:00 +00003184 BaseType = Info.Ctx.getCanonicalType(BaseType);
3185 BaseType.removeLocalConst();
Richard Smith9defb7d2018-02-21 03:38:30 +00003186 LifetimeStartedInEvaluation = true;
Richard Smith7525ff62013-05-09 07:14:00 +00003187 }
3188
Richard Smith9defb7d2018-02-21 03:38:30 +00003189 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003190 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003191 //
3192 // FIXME: Not all local state is mutable. Allow local constant subobjects
3193 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003194 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3195 Info.EvalStatus.HasSideEffects) ||
3196 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003197 return CompleteObject();
3198
Richard Smith9defb7d2018-02-21 03:38:30 +00003199 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
Richard Smith3229b742013-05-05 21:17:10 +00003200}
3201
Richard Smith243ef902013-05-05 23:31:59 +00003202/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3203/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3204/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003205///
3206/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003207/// \param Conv - The expression for which we are performing the conversion.
3208/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003209/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3210/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003211/// \param LVal - The glvalue on which we are attempting to perform this action.
3212/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003213static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003214 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003215 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003216 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003217 return false;
3218
Richard Smith3229b742013-05-05 21:17:10 +00003219 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003220 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003221 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003222 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3223 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3224 // initializer until now for such expressions. Such an expression can't be
3225 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003226 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003227 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003228 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003229 }
Richard Smith3229b742013-05-05 21:17:10 +00003230 APValue Lit;
3231 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3232 return false;
Richard Smith9defb7d2018-02-21 03:38:30 +00003233 CompleteObject LitObj(&Lit, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003234 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003235 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003236 // We represent a string literal array as an lvalue pointing at the
3237 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003238 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003239 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smith9defb7d2018-02-21 03:38:30 +00003240 CompleteObject StrObj(&Str, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003241 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003242 }
Richard Smith11562c52011-10-28 17:51:58 +00003243 }
3244
Richard Smith3229b742013-05-05 21:17:10 +00003245 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3246 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003247}
3248
3249/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003250static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003251 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003252 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003253 return false;
3254
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003255 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003256 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003257 return false;
3258 }
3259
Richard Smith3229b742013-05-05 21:17:10 +00003260 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Aaron Ballmana5038552018-01-09 13:07:03 +00003261 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3262}
3263
3264namespace {
3265struct CompoundAssignSubobjectHandler {
3266 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003267 const Expr *E;
3268 QualType PromotedLHSType;
3269 BinaryOperatorKind Opcode;
3270 const APValue &RHS;
3271
3272 static const AccessKinds AccessKind = AK_Assign;
3273
3274 typedef bool result_type;
3275
3276 bool checkConst(QualType QT) {
3277 // Assigning to a const object has undefined behavior.
3278 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003279 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003280 return false;
3281 }
3282 return true;
3283 }
3284
3285 bool failed() { return false; }
3286 bool found(APValue &Subobj, QualType SubobjType) {
3287 switch (Subobj.getKind()) {
3288 case APValue::Int:
3289 return found(Subobj.getInt(), SubobjType);
3290 case APValue::Float:
3291 return found(Subobj.getFloat(), SubobjType);
3292 case APValue::ComplexInt:
3293 case APValue::ComplexFloat:
3294 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003295 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003296 return false;
3297 case APValue::LValue:
3298 return foundPointer(Subobj, SubobjType);
3299 default:
3300 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003301 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003302 return false;
3303 }
3304 }
3305 bool found(APSInt &Value, QualType SubobjType) {
3306 if (!checkConst(SubobjType))
3307 return false;
3308
3309 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3310 // We don't support compound assignment on integer-cast-to-pointer
3311 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003312 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003313 return false;
3314 }
3315
3316 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3317 SubobjType, Value);
3318 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3319 return false;
3320 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3321 return true;
3322 }
3323 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003324 return checkConst(SubobjType) &&
3325 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3326 Value) &&
3327 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3328 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003329 }
3330 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3331 if (!checkConst(SubobjType))
3332 return false;
3333
3334 QualType PointeeType;
3335 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3336 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003337
3338 if (PointeeType.isNull() || !RHS.isInt() ||
3339 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003340 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003341 return false;
3342 }
3343
Richard Smithd6cc1982017-01-31 02:23:02 +00003344 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003345 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003346 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003347
3348 LValue LVal;
3349 LVal.setFrom(Info.Ctx, Subobj);
3350 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3351 return false;
3352 LVal.moveInto(Subobj);
3353 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003354 }
3355 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3356 llvm_unreachable("shouldn't encounter string elements here");
3357 }
3358};
3359} // end anonymous namespace
3360
3361const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3362
3363/// Perform a compound assignment of LVal <op>= RVal.
3364static bool handleCompoundAssignment(
3365 EvalInfo &Info, const Expr *E,
3366 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3367 BinaryOperatorKind Opcode, const APValue &RVal) {
3368 if (LVal.Designator.Invalid)
3369 return false;
3370
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003371 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003372 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003373 return false;
3374 }
3375
3376 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3377 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3378 RVal };
3379 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3380}
3381
Aaron Ballmana5038552018-01-09 13:07:03 +00003382namespace {
3383struct IncDecSubobjectHandler {
3384 EvalInfo &Info;
3385 const UnaryOperator *E;
3386 AccessKinds AccessKind;
3387 APValue *Old;
3388
Richard Smith243ef902013-05-05 23:31:59 +00003389 typedef bool result_type;
3390
3391 bool checkConst(QualType QT) {
3392 // Assigning to a const object has undefined behavior.
3393 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003394 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003395 return false;
3396 }
3397 return true;
3398 }
3399
3400 bool failed() { return false; }
3401 bool found(APValue &Subobj, QualType SubobjType) {
3402 // Stash the old value. Also clear Old, so we don't clobber it later
3403 // if we're post-incrementing a complex.
3404 if (Old) {
3405 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003406 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003407 }
3408
3409 switch (Subobj.getKind()) {
3410 case APValue::Int:
3411 return found(Subobj.getInt(), SubobjType);
3412 case APValue::Float:
3413 return found(Subobj.getFloat(), SubobjType);
3414 case APValue::ComplexInt:
3415 return found(Subobj.getComplexIntReal(),
3416 SubobjType->castAs<ComplexType>()->getElementType()
3417 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3418 case APValue::ComplexFloat:
3419 return found(Subobj.getComplexFloatReal(),
3420 SubobjType->castAs<ComplexType>()->getElementType()
3421 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3422 case APValue::LValue:
3423 return foundPointer(Subobj, SubobjType);
3424 default:
3425 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003426 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003427 return false;
3428 }
3429 }
3430 bool found(APSInt &Value, QualType SubobjType) {
3431 if (!checkConst(SubobjType))
3432 return false;
3433
3434 if (!SubobjType->isIntegerType()) {
3435 // We don't support increment / decrement on integer-cast-to-pointer
3436 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003437 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003438 return false;
3439 }
3440
3441 if (Old) *Old = APValue(Value);
3442
3443 // bool arithmetic promotes to int, and the conversion back to bool
3444 // doesn't reduce mod 2^n, so special-case it.
3445 if (SubobjType->isBooleanType()) {
3446 if (AccessKind == AK_Increment)
3447 Value = 1;
3448 else
3449 Value = !Value;
3450 return true;
3451 }
3452
3453 bool WasNegative = Value.isNegative();
Aaron Ballmana5038552018-01-09 13:07:03 +00003454 if (AccessKind == AK_Increment) {
3455 ++Value;
3456
3457 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3458 APSInt ActualValue(Value, /*IsUnsigned*/true);
3459 return HandleOverflow(Info, E, ActualValue, SubobjType);
3460 }
3461 } else {
3462 --Value;
3463
3464 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3465 unsigned BitWidth = Value.getBitWidth();
3466 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3467 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003468 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003469 }
3470 }
3471 return true;
3472 }
3473 bool found(APFloat &Value, QualType SubobjType) {
3474 if (!checkConst(SubobjType))
3475 return false;
3476
3477 if (Old) *Old = APValue(Value);
3478
3479 APFloat One(Value.getSemantics(), 1);
3480 if (AccessKind == AK_Increment)
3481 Value.add(One, APFloat::rmNearestTiesToEven);
3482 else
3483 Value.subtract(One, APFloat::rmNearestTiesToEven);
3484 return true;
3485 }
3486 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3487 if (!checkConst(SubobjType))
3488 return false;
3489
3490 QualType PointeeType;
3491 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3492 PointeeType = PT->getPointeeType();
3493 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003494 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003495 return false;
3496 }
3497
3498 LValue LVal;
3499 LVal.setFrom(Info.Ctx, Subobj);
3500 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3501 AccessKind == AK_Increment ? 1 : -1))
3502 return false;
3503 LVal.moveInto(Subobj);
3504 return true;
3505 }
3506 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3507 llvm_unreachable("shouldn't encounter string elements here");
3508 }
3509};
3510} // end anonymous namespace
3511
3512/// Perform an increment or decrement on LVal.
3513static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3514 QualType LValType, bool IsIncrement, APValue *Old) {
3515 if (LVal.Designator.Invalid)
3516 return false;
3517
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003518 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003519 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003520 return false;
3521 }
Aaron Ballmana5038552018-01-09 13:07:03 +00003522
3523 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3524 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3525 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3526 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3527}
3528
Richard Smithe97cbd72011-11-11 04:05:33 +00003529/// Build an lvalue for the object argument of a member function call.
3530static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3531 LValue &This) {
3532 if (Object->getType()->isPointerType())
3533 return EvaluatePointer(Object, This, Info);
3534
3535 if (Object->isGLValue())
3536 return EvaluateLValue(Object, This, Info);
3537
Richard Smithd9f663b2013-04-22 15:31:51 +00003538 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003539 return EvaluateTemporary(Object, This, Info);
3540
Faisal Valie690b7a2016-07-02 22:34:24 +00003541 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003542 return false;
3543}
3544
3545/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3546/// lvalue referring to the result.
3547///
3548/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003549/// \param LV - An lvalue referring to the base of the member pointer.
3550/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003551/// \param IncludeMember - Specifies whether the member itself is included in
3552/// the resulting LValue subobject designator. This is not possible when
3553/// creating a bound member function.
3554/// \return The field or method declaration to which the member pointer refers,
3555/// or 0 if evaluation fails.
3556static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003557 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003558 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003559 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003560 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003561 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003562 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003563 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003564
3565 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3566 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003567 if (!MemPtr.getDecl()) {
3568 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003569 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003570 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003571 }
Richard Smith253c2a32012-01-27 01:14:48 +00003572
Richard Smith027bf112011-11-17 22:56:20 +00003573 if (MemPtr.isDerivedMember()) {
3574 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003575 // The end of the derived-to-base path for the base object must match the
3576 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003577 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003578 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003579 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003580 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003581 }
Richard Smith027bf112011-11-17 22:56:20 +00003582 unsigned PathLengthToMember =
3583 LV.Designator.Entries.size() - MemPtr.Path.size();
3584 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3585 const CXXRecordDecl *LVDecl = getAsBaseClass(
3586 LV.Designator.Entries[PathLengthToMember + I]);
3587 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003588 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003589 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003590 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003591 }
Richard Smith027bf112011-11-17 22:56:20 +00003592 }
3593
3594 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003595 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003596 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003597 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003598 } else if (!MemPtr.Path.empty()) {
3599 // Extend the LValue path with the member pointer's path.
3600 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3601 MemPtr.Path.size() + IncludeMember);
3602
3603 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003604 if (const PointerType *PT = LVType->getAs<PointerType>())
3605 LVType = PT->getPointeeType();
3606 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3607 assert(RD && "member pointer access on non-class-type expression");
3608 // The first class in the path is that of the lvalue.
3609 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3610 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003611 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003612 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003613 RD = Base;
3614 }
3615 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003616 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3617 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003618 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003619 }
3620
3621 // Add the member. Note that we cannot build bound member functions here.
3622 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003623 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003624 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003625 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003626 } else if (const IndirectFieldDecl *IFD =
3627 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003628 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003629 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003630 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003631 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003632 }
Richard Smith027bf112011-11-17 22:56:20 +00003633 }
3634
3635 return MemPtr.getDecl();
3636}
3637
Richard Smith84401042013-06-03 05:03:02 +00003638static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3639 const BinaryOperator *BO,
3640 LValue &LV,
3641 bool IncludeMember = true) {
3642 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3643
3644 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003645 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003646 MemberPtr MemPtr;
3647 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3648 }
Craig Topper36250ad2014-05-12 05:36:57 +00003649 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003650 }
3651
3652 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3653 BO->getRHS(), IncludeMember);
3654}
3655
Richard Smith027bf112011-11-17 22:56:20 +00003656/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3657/// the provided lvalue, which currently refers to the base object.
3658static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3659 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003660 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003661 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003662 return false;
3663
Richard Smitha8105bc2012-01-06 16:39:00 +00003664 QualType TargetQT = E->getType();
3665 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3666 TargetQT = PT->getPointeeType();
3667
3668 // Check this cast lands within the final derived-to-base subobject path.
3669 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003670 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003671 << D.MostDerivedType << TargetQT;
3672 return false;
3673 }
3674
Richard Smith027bf112011-11-17 22:56:20 +00003675 // Check the type of the final cast. We don't need to check the path,
3676 // since a cast can only be formed if the path is unique.
3677 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003678 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3679 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003680 if (NewEntriesSize == D.MostDerivedPathLength)
3681 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3682 else
Richard Smith027bf112011-11-17 22:56:20 +00003683 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003684 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003685 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003686 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003687 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003688 }
Richard Smith027bf112011-11-17 22:56:20 +00003689
3690 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003691 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003692}
3693
Mike Stump876387b2009-10-27 22:09:17 +00003694namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003695enum EvalStmtResult {
3696 /// Evaluation failed.
3697 ESR_Failed,
3698 /// Hit a 'return' statement.
3699 ESR_Returned,
3700 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003701 ESR_Succeeded,
3702 /// Hit a 'continue' statement.
3703 ESR_Continue,
3704 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003705 ESR_Break,
3706 /// Still scanning for 'case' or 'default' statement.
3707 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003708};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003709}
Richard Smith254a73d2011-10-28 22:34:42 +00003710
Richard Smith97fcf4b2016-08-14 23:15:52 +00003711static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3712 // We don't need to evaluate the initializer for a static local.
3713 if (!VD->hasLocalStorage())
3714 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003715
Richard Smith97fcf4b2016-08-14 23:15:52 +00003716 LValue Result;
3717 Result.set(VD, Info.CurrentCall->Index);
3718 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003719
Richard Smith97fcf4b2016-08-14 23:15:52 +00003720 const Expr *InitE = VD->getInit();
3721 if (!InitE) {
3722 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3723 << false << VD->getType();
3724 Val = APValue();
3725 return false;
3726 }
Richard Smith51f03172013-06-20 03:00:05 +00003727
Richard Smith97fcf4b2016-08-14 23:15:52 +00003728 if (InitE->isValueDependent())
3729 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003730
Richard Smith97fcf4b2016-08-14 23:15:52 +00003731 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3732 // Wipe out any partially-computed value, to allow tracking that this
3733 // evaluation failed.
3734 Val = APValue();
3735 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003736 }
3737
3738 return true;
3739}
3740
Richard Smith97fcf4b2016-08-14 23:15:52 +00003741static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3742 bool OK = true;
3743
3744 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3745 OK &= EvaluateVarDecl(Info, VD);
3746
3747 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3748 for (auto *BD : DD->bindings())
3749 if (auto *VD = BD->getHoldingVar())
3750 OK &= EvaluateDecl(Info, VD);
3751
3752 return OK;
3753}
3754
3755
Richard Smith4e18ca52013-05-06 05:56:11 +00003756/// Evaluate a condition (either a variable declaration or an expression).
3757static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3758 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003759 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003760 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3761 return false;
3762 return EvaluateAsBooleanCondition(Cond, Result, Info);
3763}
3764
Richard Smith89210072016-04-04 23:29:43 +00003765namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003766/// \brief A location where the result (returned value) of evaluating a
3767/// statement should be stored.
3768struct StmtResult {
3769 /// The APValue that should be filled in with the returned value.
3770 APValue &Value;
3771 /// The location containing the result, if any (used to support RVO).
3772 const LValue *Slot;
3773};
Richard Smith89210072016-04-04 23:29:43 +00003774}
Richard Smith52a980a2015-08-28 02:43:42 +00003775
3776static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003777 const Stmt *S,
3778 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003779
3780/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003781static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003782 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003783 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003784 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003785 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003786 case ESR_Break:
3787 return ESR_Succeeded;
3788 case ESR_Succeeded:
3789 case ESR_Continue:
3790 return ESR_Continue;
3791 case ESR_Failed:
3792 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003793 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003794 return ESR;
3795 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003796 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003797}
3798
Richard Smith496ddcf2013-05-12 17:32:42 +00003799/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003800static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003801 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003802 BlockScopeRAII Scope(Info);
3803
Richard Smith496ddcf2013-05-12 17:32:42 +00003804 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003805 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003806 {
3807 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003808 if (const Stmt *Init = SS->getInit()) {
3809 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3810 if (ESR != ESR_Succeeded)
3811 return ESR;
3812 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003813 if (SS->getConditionVariable() &&
3814 !EvaluateDecl(Info, SS->getConditionVariable()))
3815 return ESR_Failed;
3816 if (!EvaluateInteger(SS->getCond(), Value, Info))
3817 return ESR_Failed;
3818 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003819
3820 // Find the switch case corresponding to the value of the condition.
3821 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003822 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003823 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3824 SC = SC->getNextSwitchCase()) {
3825 if (isa<DefaultStmt>(SC)) {
3826 Found = SC;
3827 continue;
3828 }
3829
3830 const CaseStmt *CS = cast<CaseStmt>(SC);
3831 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3832 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3833 : LHS;
3834 if (LHS <= Value && Value <= RHS) {
3835 Found = SC;
3836 break;
3837 }
3838 }
3839
3840 if (!Found)
3841 return ESR_Succeeded;
3842
3843 // Search the switch body for the switch case and evaluate it from there.
3844 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3845 case ESR_Break:
3846 return ESR_Succeeded;
3847 case ESR_Succeeded:
3848 case ESR_Continue:
3849 case ESR_Failed:
3850 case ESR_Returned:
3851 return ESR;
3852 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003853 // This can only happen if the switch case is nested within a statement
3854 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003855 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003856 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003857 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003858 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003859}
3860
Richard Smith254a73d2011-10-28 22:34:42 +00003861// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003862static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003863 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003864 if (!Info.nextStep(S))
3865 return ESR_Failed;
3866
Richard Smith496ddcf2013-05-12 17:32:42 +00003867 // If we're hunting down a 'case' or 'default' label, recurse through
3868 // substatements until we hit the label.
3869 if (Case) {
3870 // FIXME: We don't start the lifetime of objects whose initialization we
3871 // jump over. However, such objects must be of class type with a trivial
3872 // default constructor that initialize all subobjects, so must be empty,
3873 // so this almost never matters.
3874 switch (S->getStmtClass()) {
3875 case Stmt::CompoundStmtClass:
3876 // FIXME: Precompute which substatement of a compound statement we
3877 // would jump to, and go straight there rather than performing a
3878 // linear scan each time.
3879 case Stmt::LabelStmtClass:
3880 case Stmt::AttributedStmtClass:
3881 case Stmt::DoStmtClass:
3882 break;
3883
3884 case Stmt::CaseStmtClass:
3885 case Stmt::DefaultStmtClass:
3886 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003887 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003888 break;
3889
3890 case Stmt::IfStmtClass: {
3891 // FIXME: Precompute which side of an 'if' we would jump to, and go
3892 // straight there rather than scanning both sides.
3893 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003894
3895 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3896 // preceded by our switch label.
3897 BlockScopeRAII Scope(Info);
3898
Richard Smith496ddcf2013-05-12 17:32:42 +00003899 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3900 if (ESR != ESR_CaseNotFound || !IS->getElse())
3901 return ESR;
3902 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3903 }
3904
3905 case Stmt::WhileStmtClass: {
3906 EvalStmtResult ESR =
3907 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3908 if (ESR != ESR_Continue)
3909 return ESR;
3910 break;
3911 }
3912
3913 case Stmt::ForStmtClass: {
3914 const ForStmt *FS = cast<ForStmt>(S);
3915 EvalStmtResult ESR =
3916 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3917 if (ESR != ESR_Continue)
3918 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003919 if (FS->getInc()) {
3920 FullExpressionRAII IncScope(Info);
3921 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3922 return ESR_Failed;
3923 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003924 break;
3925 }
3926
3927 case Stmt::DeclStmtClass:
3928 // FIXME: If the variable has initialization that can't be jumped over,
3929 // bail out of any immediately-surrounding compound-statement too.
3930 default:
3931 return ESR_CaseNotFound;
3932 }
3933 }
3934
Richard Smith254a73d2011-10-28 22:34:42 +00003935 switch (S->getStmtClass()) {
3936 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003937 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003938 // Don't bother evaluating beyond an expression-statement which couldn't
3939 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003940 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003941 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003942 return ESR_Failed;
3943 return ESR_Succeeded;
3944 }
3945
Faisal Valie690b7a2016-07-02 22:34:24 +00003946 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003947 return ESR_Failed;
3948
3949 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003950 return ESR_Succeeded;
3951
Richard Smithd9f663b2013-04-22 15:31:51 +00003952 case Stmt::DeclStmtClass: {
3953 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003954 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003955 // Each declaration initialization is its own full-expression.
3956 // FIXME: This isn't quite right; if we're performing aggregate
3957 // initialization, each braced subexpression is its own full-expression.
3958 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003959 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003960 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003961 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003962 return ESR_Succeeded;
3963 }
3964
Richard Smith357362d2011-12-13 06:39:58 +00003965 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003966 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003967 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003968 if (RetExpr &&
3969 !(Result.Slot
3970 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3971 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003972 return ESR_Failed;
3973 return ESR_Returned;
3974 }
Richard Smith254a73d2011-10-28 22:34:42 +00003975
3976 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003977 BlockScopeRAII Scope(Info);
3978
Richard Smith254a73d2011-10-28 22:34:42 +00003979 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003980 for (const auto *BI : CS->body()) {
3981 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003982 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003983 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003984 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003985 return ESR;
3986 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003987 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003988 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003989
3990 case Stmt::IfStmtClass: {
3991 const IfStmt *IS = cast<IfStmt>(S);
3992
3993 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003994 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003995 if (const Stmt *Init = IS->getInit()) {
3996 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3997 if (ESR != ESR_Succeeded)
3998 return ESR;
3999 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004000 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004001 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004002 return ESR_Failed;
4003
4004 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4005 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4006 if (ESR != ESR_Succeeded)
4007 return ESR;
4008 }
4009 return ESR_Succeeded;
4010 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004011
4012 case Stmt::WhileStmtClass: {
4013 const WhileStmt *WS = cast<WhileStmt>(S);
4014 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004015 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004016 bool Continue;
4017 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4018 Continue))
4019 return ESR_Failed;
4020 if (!Continue)
4021 break;
4022
4023 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4024 if (ESR != ESR_Continue)
4025 return ESR;
4026 }
4027 return ESR_Succeeded;
4028 }
4029
4030 case Stmt::DoStmtClass: {
4031 const DoStmt *DS = cast<DoStmt>(S);
4032 bool Continue;
4033 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004034 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004035 if (ESR != ESR_Continue)
4036 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004037 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004038
Richard Smith08d6a2c2013-07-24 07:11:57 +00004039 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004040 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4041 return ESR_Failed;
4042 } while (Continue);
4043 return ESR_Succeeded;
4044 }
4045
4046 case Stmt::ForStmtClass: {
4047 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004048 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004049 if (FS->getInit()) {
4050 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4051 if (ESR != ESR_Succeeded)
4052 return ESR;
4053 }
4054 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004055 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004056 bool Continue = true;
4057 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4058 FS->getCond(), Continue))
4059 return ESR_Failed;
4060 if (!Continue)
4061 break;
4062
4063 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4064 if (ESR != ESR_Continue)
4065 return ESR;
4066
Richard Smith08d6a2c2013-07-24 07:11:57 +00004067 if (FS->getInc()) {
4068 FullExpressionRAII IncScope(Info);
4069 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4070 return ESR_Failed;
4071 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004072 }
4073 return ESR_Succeeded;
4074 }
4075
Richard Smith896e0d72013-05-06 06:51:17 +00004076 case Stmt::CXXForRangeStmtClass: {
4077 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004078 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004079
4080 // Initialize the __range variable.
4081 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4082 if (ESR != ESR_Succeeded)
4083 return ESR;
4084
4085 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004086 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4087 if (ESR != ESR_Succeeded)
4088 return ESR;
4089 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004090 if (ESR != ESR_Succeeded)
4091 return ESR;
4092
4093 while (true) {
4094 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004095 {
4096 bool Continue = true;
4097 FullExpressionRAII CondExpr(Info);
4098 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4099 return ESR_Failed;
4100 if (!Continue)
4101 break;
4102 }
Richard Smith896e0d72013-05-06 06:51:17 +00004103
4104 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004105 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004106 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4107 if (ESR != ESR_Succeeded)
4108 return ESR;
4109
4110 // Loop body.
4111 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4112 if (ESR != ESR_Continue)
4113 return ESR;
4114
4115 // Increment: ++__begin
4116 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4117 return ESR_Failed;
4118 }
4119
4120 return ESR_Succeeded;
4121 }
4122
Richard Smith496ddcf2013-05-12 17:32:42 +00004123 case Stmt::SwitchStmtClass:
4124 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4125
Richard Smith4e18ca52013-05-06 05:56:11 +00004126 case Stmt::ContinueStmtClass:
4127 return ESR_Continue;
4128
4129 case Stmt::BreakStmtClass:
4130 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004131
4132 case Stmt::LabelStmtClass:
4133 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4134
4135 case Stmt::AttributedStmtClass:
4136 // As a general principle, C++11 attributes can be ignored without
4137 // any semantic impact.
4138 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4139 Case);
4140
4141 case Stmt::CaseStmtClass:
4142 case Stmt::DefaultStmtClass:
4143 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004144 }
4145}
4146
Richard Smithcc36f692011-12-22 02:22:31 +00004147/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4148/// default constructor. If so, we'll fold it whether or not it's marked as
4149/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4150/// so we need special handling.
4151static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004152 const CXXConstructorDecl *CD,
4153 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004154 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4155 return false;
4156
Richard Smith66e05fe2012-01-18 05:21:49 +00004157 // Value-initialization does not call a trivial default constructor, so such a
4158 // call is a core constant expression whether or not the constructor is
4159 // constexpr.
4160 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004161 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004162 // FIXME: If DiagDecl is an implicitly-declared special member function,
4163 // we should be much more explicit about why it's not constexpr.
4164 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4165 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4166 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004167 } else {
4168 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4169 }
4170 }
4171 return true;
4172}
4173
Richard Smith357362d2011-12-13 06:39:58 +00004174/// CheckConstexprFunction - Check that a function can be called in a constant
4175/// expression.
4176static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4177 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004178 const FunctionDecl *Definition,
4179 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004180 // Potential constant expressions can contain calls to declared, but not yet
4181 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004182 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004183 Declaration->isConstexpr())
4184 return false;
4185
Richard Smith0838f3a2013-05-14 05:18:44 +00004186 // Bail out with no diagnostic if the function declaration itself is invalid.
4187 // We will have produced a relevant diagnostic while parsing it.
4188 if (Declaration->isInvalidDecl())
4189 return false;
4190
Richard Smith357362d2011-12-13 06:39:58 +00004191 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004192 if (Definition && Definition->isConstexpr() &&
4193 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004194 return true;
4195
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004196 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004197 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Daniel Jasperffdee092017-05-02 19:21:42 +00004198
Richard Smith5179eb72016-06-28 19:03:57 +00004199 // If this function is not constexpr because it is an inherited
4200 // non-constexpr constructor, diagnose that directly.
4201 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4202 if (CD && CD->isInheritingConstructor()) {
4203 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Daniel Jasperffdee092017-05-02 19:21:42 +00004204 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004205 DiagDecl = CD = Inherited;
4206 }
4207
4208 // FIXME: If DiagDecl is an implicitly-declared special member function
4209 // or an inheriting constructor, we should be much more explicit about why
4210 // it's not constexpr.
4211 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004212 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004213 << CD->getInheritedConstructor().getConstructor()->getParent();
4214 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004215 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004216 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004217 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4218 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004219 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004220 }
4221 return false;
4222}
4223
Richard Smithbe6dd812014-11-19 21:27:17 +00004224/// Determine if a class has any fields that might need to be copied by a
4225/// trivial copy or move operation.
4226static bool hasFields(const CXXRecordDecl *RD) {
4227 if (!RD || RD->isEmpty())
4228 return false;
4229 for (auto *FD : RD->fields()) {
4230 if (FD->isUnnamedBitfield())
4231 continue;
4232 return true;
4233 }
4234 for (auto &Base : RD->bases())
4235 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4236 return true;
4237 return false;
4238}
4239
Richard Smithd62306a2011-11-10 06:34:14 +00004240namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004241typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004242}
4243
4244/// EvaluateArgs - Evaluate the arguments to a function call.
4245static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4246 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004247 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004248 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004249 I != E; ++I) {
4250 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4251 // If we're checking for a potential constant expression, evaluate all
4252 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004253 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004254 return false;
4255 Success = false;
4256 }
4257 }
4258 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004259}
4260
Richard Smith254a73d2011-10-28 22:34:42 +00004261/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004262static bool HandleFunctionCall(SourceLocation CallLoc,
4263 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004264 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004265 EvalInfo &Info, APValue &Result,
4266 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004267 ArgVector ArgValues(Args.size());
4268 if (!EvaluateArgs(Args, ArgValues, Info))
4269 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004270
Richard Smith253c2a32012-01-27 01:14:48 +00004271 if (!Info.CheckCallLimit(CallLoc))
4272 return false;
4273
4274 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004275
4276 // For a trivial copy or move assignment, perform an APValue copy. This is
4277 // essential for unions, where the operations performed by the assignment
4278 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004279 //
4280 // Skip this for non-union classes with no fields; in that case, the defaulted
4281 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004282 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004283 if (MD && MD->isDefaulted() &&
4284 (MD->getParent()->isUnion() ||
4285 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004286 assert(This &&
4287 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4288 LValue RHS;
4289 RHS.setFrom(Info.Ctx, ArgValues[0]);
4290 APValue RHSValue;
4291 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4292 RHS, RHSValue))
4293 return false;
4294 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4295 RHSValue))
4296 return false;
4297 This->moveInto(Result);
4298 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004299 } else if (MD && isLambdaCallOperator(MD)) {
4300 // We're in a lambda; determine the lambda capture field maps.
4301 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4302 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004303 }
4304
Richard Smith52a980a2015-08-28 02:43:42 +00004305 StmtResult Ret = {Result, ResultSlot};
4306 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004307 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004308 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004309 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004310 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004311 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004312 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004313}
4314
Richard Smithd62306a2011-11-10 06:34:14 +00004315/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004316static bool HandleConstructorCall(const Expr *E, const LValue &This,
4317 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004318 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004319 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004320 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004321 if (!Info.CheckCallLimit(CallLoc))
4322 return false;
4323
Richard Smith3607ffe2012-02-13 03:54:03 +00004324 const CXXRecordDecl *RD = Definition->getParent();
4325 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004326 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004327 return false;
4328 }
4329
Erik Pilkington42925492017-10-04 00:18:55 +00004330 EvalInfo::EvaluatingConstructorRAII EvalObj(
4331 Info, {This.getLValueBase(), This.CallIndex});
Richard Smith5179eb72016-06-28 19:03:57 +00004332 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004333
Richard Smith52a980a2015-08-28 02:43:42 +00004334 // FIXME: Creating an APValue just to hold a nonexistent return value is
4335 // wasteful.
4336 APValue RetVal;
4337 StmtResult Ret = {RetVal, nullptr};
4338
Richard Smith5179eb72016-06-28 19:03:57 +00004339 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004340 if (Definition->isDelegatingConstructor()) {
4341 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004342 {
4343 FullExpressionRAII InitScope(Info);
4344 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4345 return false;
4346 }
Richard Smith52a980a2015-08-28 02:43:42 +00004347 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004348 }
4349
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004350 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004351 // essential for unions (or classes with anonymous union members), where the
4352 // operations performed by the constructor cannot be represented by
4353 // ctor-initializers.
4354 //
4355 // Skip this for empty non-union classes; we should not perform an
4356 // lvalue-to-rvalue conversion on them because their copy constructor does not
4357 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004358 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004359 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004360 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004361 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004362 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004363 return handleLValueToRValueConversion(
4364 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4365 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004366 }
4367
4368 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004369 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004370 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004371 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004372
John McCalld7bca762012-05-01 00:38:49 +00004373 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004374 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4375
Richard Smith08d6a2c2013-07-24 07:11:57 +00004376 // A scope for temporaries lifetime-extended by reference members.
4377 BlockScopeRAII LifetimeExtendedScope(Info);
4378
Richard Smith253c2a32012-01-27 01:14:48 +00004379 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004380 unsigned BasesSeen = 0;
4381#ifndef NDEBUG
4382 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4383#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004384 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004385 LValue Subobject = This;
4386 APValue *Value = &Result;
4387
4388 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004389 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004390 if (I->isBaseInitializer()) {
4391 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004392#ifndef NDEBUG
4393 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004394 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004395 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4396 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4397 "base class initializers not in expected order");
4398 ++BaseIt;
4399#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004400 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004401 BaseType->getAsCXXRecordDecl(), &Layout))
4402 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004403 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004404 } else if ((FD = I->getMember())) {
4405 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004406 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004407 if (RD->isUnion()) {
4408 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004409 Value = &Result.getUnionValue();
4410 } else {
4411 Value = &Result.getStructField(FD->getFieldIndex());
4412 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004413 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004414 // Walk the indirect field decl's chain to find the object to initialize,
4415 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004416 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004417 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004418 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4419 // Switch the union field if it differs. This happens if we had
4420 // preceding zero-initialization, and we're now initializing a union
4421 // subobject other than the first.
4422 // FIXME: In this case, the values of the other subobjects are
4423 // specified, since zero-initialization sets all padding bits to zero.
4424 if (Value->isUninit() ||
4425 (Value->isUnion() && Value->getUnionField() != FD)) {
4426 if (CD->isUnion())
4427 *Value = APValue(FD);
4428 else
4429 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004430 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004431 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004432 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004433 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004434 if (CD->isUnion())
4435 Value = &Value->getUnionValue();
4436 else
4437 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004438 }
Richard Smithd62306a2011-11-10 06:34:14 +00004439 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004440 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004441 }
Richard Smith253c2a32012-01-27 01:14:48 +00004442
Richard Smith08d6a2c2013-07-24 07:11:57 +00004443 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004444 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4445 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004446 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004447 // If we're checking for a potential constant expression, evaluate all
4448 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004449 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004450 return false;
4451 Success = false;
4452 }
Richard Smithd62306a2011-11-10 06:34:14 +00004453 }
4454
Richard Smithd9f663b2013-04-22 15:31:51 +00004455 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004456 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004457}
4458
Richard Smith5179eb72016-06-28 19:03:57 +00004459static bool HandleConstructorCall(const Expr *E, const LValue &This,
4460 ArrayRef<const Expr*> Args,
4461 const CXXConstructorDecl *Definition,
4462 EvalInfo &Info, APValue &Result) {
4463 ArgVector ArgValues(Args.size());
4464 if (!EvaluateArgs(Args, ArgValues, Info))
4465 return false;
4466
4467 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4468 Info, Result);
4469}
4470
Eli Friedman9a156e52008-11-12 09:44:48 +00004471//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004472// Generic Evaluation
4473//===----------------------------------------------------------------------===//
4474namespace {
4475
Aaron Ballman68af21c2014-01-03 19:26:43 +00004476template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004477class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004478 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004479private:
Richard Smith52a980a2015-08-28 02:43:42 +00004480 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004481 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004482 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004483 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004484 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004485 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004486 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004487
Richard Smith17100ba2012-02-16 02:46:34 +00004488 // Check whether a conditional operator with a non-constant condition is a
4489 // potential constant expression. If neither arm is a potential constant
4490 // expression, then the conditional operator is not either.
4491 template<typename ConditionalOperator>
4492 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004493 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004494
4495 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004496 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004497 {
Richard Smith17100ba2012-02-16 02:46:34 +00004498 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004499 StmtVisitorTy::Visit(E->getFalseExpr());
4500 if (Diag.empty())
4501 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004502 }
Richard Smith17100ba2012-02-16 02:46:34 +00004503
George Burgess IV8c892b52016-05-25 22:31:54 +00004504 {
4505 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004506 Diag.clear();
4507 StmtVisitorTy::Visit(E->getTrueExpr());
4508 if (Diag.empty())
4509 return;
4510 }
4511
4512 Error(E, diag::note_constexpr_conditional_never_const);
4513 }
4514
4515
4516 template<typename ConditionalOperator>
4517 bool HandleConditionalOperator(const ConditionalOperator *E) {
4518 bool BoolResult;
4519 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004520 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004521 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004522 return false;
4523 }
4524 if (Info.noteFailure()) {
4525 StmtVisitorTy::Visit(E->getTrueExpr());
4526 StmtVisitorTy::Visit(E->getFalseExpr());
4527 }
Richard Smith17100ba2012-02-16 02:46:34 +00004528 return false;
4529 }
4530
4531 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4532 return StmtVisitorTy::Visit(EvalExpr);
4533 }
4534
Peter Collingbournee9200682011-05-13 03:29:01 +00004535protected:
4536 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004537 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004538 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4539
Richard Smith92b1ce02011-12-12 09:28:41 +00004540 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004541 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004542 }
4543
Aaron Ballman68af21c2014-01-03 19:26:43 +00004544 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004545
4546public:
4547 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4548
4549 EvalInfo &getEvalInfo() { return Info; }
4550
Richard Smithf57d8cb2011-12-09 22:58:01 +00004551 /// Report an evaluation error. This should only be called when an error is
4552 /// first discovered. When propagating an error, just return false.
4553 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004554 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004555 return false;
4556 }
4557 bool Error(const Expr *E) {
4558 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4559 }
4560
Aaron Ballman68af21c2014-01-03 19:26:43 +00004561 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004562 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004563 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004564 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004565 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004566 }
4567
Aaron Ballman68af21c2014-01-03 19:26:43 +00004568 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004569 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004570 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004571 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004572 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004573 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004574 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004575 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004576 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004577 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004578 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004579 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004580 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004581 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004582 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004583 // The initializer may not have been parsed yet, or might be erroneous.
4584 if (!E->getExpr())
4585 return Error(E);
4586 return StmtVisitorTy::Visit(E->getExpr());
4587 }
Richard Smith5894a912011-12-19 22:12:41 +00004588 // We cannot create any objects for which cleanups are required, so there is
4589 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004590 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004591 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004592
Aaron Ballman68af21c2014-01-03 19:26:43 +00004593 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004594 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4595 return static_cast<Derived*>(this)->VisitCastExpr(E);
4596 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004597 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004598 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4599 return static_cast<Derived*>(this)->VisitCastExpr(E);
4600 }
4601
Aaron Ballman68af21c2014-01-03 19:26:43 +00004602 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004603 switch (E->getOpcode()) {
4604 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004605 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004606
4607 case BO_Comma:
4608 VisitIgnoredValue(E->getLHS());
4609 return StmtVisitorTy::Visit(E->getRHS());
4610
4611 case BO_PtrMemD:
4612 case BO_PtrMemI: {
4613 LValue Obj;
4614 if (!HandleMemberPointerAccess(Info, E, Obj))
4615 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004616 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004617 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004618 return false;
4619 return DerivedSuccess(Result, E);
4620 }
4621 }
4622 }
4623
Aaron Ballman68af21c2014-01-03 19:26:43 +00004624 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004625 // Evaluate and cache the common expression. We treat it as a temporary,
4626 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004627 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004628 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004629 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004630
Richard Smith17100ba2012-02-16 02:46:34 +00004631 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004632 }
4633
Aaron Ballman68af21c2014-01-03 19:26:43 +00004634 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004635 bool IsBcpCall = false;
4636 // If the condition (ignoring parens) is a __builtin_constant_p call,
4637 // the result is a constant expression if it can be folded without
4638 // side-effects. This is an important GNU extension. See GCC PR38377
4639 // for discussion.
4640 if (const CallExpr *CallCE =
4641 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004642 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004643 IsBcpCall = true;
4644
4645 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4646 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004647 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004648 return false;
4649
Richard Smith6d4c6582013-11-05 22:18:15 +00004650 FoldConstant Fold(Info, IsBcpCall);
4651 if (!HandleConditionalOperator(E)) {
4652 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004653 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004654 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004655
4656 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004657 }
4658
Aaron Ballman68af21c2014-01-03 19:26:43 +00004659 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004660 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4661 return DerivedSuccess(*Value, E);
4662
4663 const Expr *Source = E->getSourceExpr();
4664 if (!Source)
4665 return Error(E);
4666 if (Source == E) { // sanity checking.
4667 assert(0 && "OpaqueValueExpr recursively refers to itself");
4668 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004669 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004670 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004671 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004672
Aaron Ballman68af21c2014-01-03 19:26:43 +00004673 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004674 APValue Result;
4675 if (!handleCallExpr(E, Result, nullptr))
4676 return false;
4677 return DerivedSuccess(Result, E);
4678 }
4679
4680 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004681 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004682 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004683 QualType CalleeType = Callee->getType();
4684
Craig Topper36250ad2014-05-12 05:36:57 +00004685 const FunctionDecl *FD = nullptr;
4686 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004687 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004688 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004689
Richard Smithe97cbd72011-11-11 04:05:33 +00004690 // Extract function decl and 'this' pointer from the callee.
4691 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004692 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004693 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4694 // Explicit bound member calls, such as x.f() or p->g();
4695 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004696 return false;
4697 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004698 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004699 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004700 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4701 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004702 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4703 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004704 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004705 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004706 return Error(Callee);
4707
4708 FD = dyn_cast<FunctionDecl>(Member);
4709 if (!FD)
4710 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004711 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004712 LValue Call;
4713 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004714 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004715
Richard Smitha8105bc2012-01-06 16:39:00 +00004716 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004717 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004718 FD = dyn_cast_or_null<FunctionDecl>(
4719 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004720 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004721 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004722 // Don't call function pointers which have been cast to some other type.
4723 // Per DR (no number yet), the caller and callee can differ in noexcept.
4724 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4725 CalleeType->getPointeeType(), FD->getType())) {
4726 return Error(E);
4727 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004728
4729 // Overloaded operator calls to member functions are represented as normal
4730 // calls with '*this' as the first argument.
4731 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4732 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004733 // FIXME: When selecting an implicit conversion for an overloaded
4734 // operator delete, we sometimes try to evaluate calls to conversion
4735 // operators without a 'this' parameter!
4736 if (Args.empty())
4737 return Error(E);
4738
Nick Lewycky13073a62017-06-12 21:15:44 +00004739 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004740 return false;
4741 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004742 Args = Args.slice(1);
Daniel Jasperffdee092017-05-02 19:21:42 +00004743 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004744 // Map the static invoker for the lambda back to the call operator.
4745 // Conveniently, we don't have to slice out the 'this' argument (as is
4746 // being done for the non-static case), since a static member function
4747 // doesn't have an implicit argument passed in.
4748 const CXXRecordDecl *ClosureClass = MD->getParent();
4749 assert(
4750 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4751 "Number of captures must be zero for conversion to function-ptr");
4752
4753 const CXXMethodDecl *LambdaCallOp =
4754 ClosureClass->getLambdaCallOperator();
4755
4756 // Set 'FD', the function that will be called below, to the call
4757 // operator. If the closure object represents a generic lambda, find
4758 // the corresponding specialization of the call operator.
4759
4760 if (ClosureClass->isGenericLambda()) {
4761 assert(MD->isFunctionTemplateSpecialization() &&
4762 "A generic lambda's static-invoker function must be a "
4763 "template specialization");
4764 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4765 FunctionTemplateDecl *CallOpTemplate =
4766 LambdaCallOp->getDescribedFunctionTemplate();
4767 void *InsertPos = nullptr;
4768 FunctionDecl *CorrespondingCallOpSpecialization =
4769 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4770 assert(CorrespondingCallOpSpecialization &&
4771 "We must always have a function call operator specialization "
4772 "that corresponds to our static invoker specialization");
4773 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4774 } else
4775 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004776 }
4777
Daniel Jasperffdee092017-05-02 19:21:42 +00004778
Richard Smithe97cbd72011-11-11 04:05:33 +00004779 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004780 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004781
Richard Smith47b34932012-02-01 02:39:43 +00004782 if (This && !This->checkSubobject(Info, E, CSK_This))
4783 return false;
4784
Richard Smith3607ffe2012-02-13 03:54:03 +00004785 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4786 // calls to such functions in constant expressions.
4787 if (This && !HasQualifier &&
4788 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4789 return Error(E, diag::note_constexpr_virtual_call);
4790
Craig Topper36250ad2014-05-12 05:36:57 +00004791 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004792 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004793
Nick Lewycky13073a62017-06-12 21:15:44 +00004794 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4795 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004796 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004797 return false;
4798
Richard Smith52a980a2015-08-28 02:43:42 +00004799 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004800 }
4801
Aaron Ballman68af21c2014-01-03 19:26:43 +00004802 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004803 return StmtVisitorTy::Visit(E->getInitializer());
4804 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004805 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004806 if (E->getNumInits() == 0)
4807 return DerivedZeroInitialization(E);
4808 if (E->getNumInits() == 1)
4809 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004810 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004811 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004812 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004813 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004814 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004815 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004816 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004817 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004818 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004819 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004820 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004821
Richard Smithd62306a2011-11-10 06:34:14 +00004822 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004823 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004824 assert(!E->isArrow() && "missing call to bound member function?");
4825
Richard Smith2e312c82012-03-03 22:46:17 +00004826 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004827 if (!Evaluate(Val, Info, E->getBase()))
4828 return false;
4829
4830 QualType BaseTy = E->getBase()->getType();
4831
4832 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004833 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004834 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004835 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004836 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4837
Richard Smith9defb7d2018-02-21 03:38:30 +00004838 CompleteObject Obj(&Val, BaseTy, true);
Richard Smitha8105bc2012-01-06 16:39:00 +00004839 SubobjectDesignator Designator(BaseTy);
4840 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004841
Richard Smith3229b742013-05-05 21:17:10 +00004842 APValue Result;
4843 return extractSubobject(Info, E, Obj, Designator, Result) &&
4844 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004845 }
4846
Aaron Ballman68af21c2014-01-03 19:26:43 +00004847 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004848 switch (E->getCastKind()) {
4849 default:
4850 break;
4851
Richard Smitha23ab512013-05-23 00:30:41 +00004852 case CK_AtomicToNonAtomic: {
4853 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004854 // This does not need to be done in place even for class/array types:
4855 // atomic-to-non-atomic conversion implies copying the object
4856 // representation.
4857 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004858 return false;
4859 return DerivedSuccess(AtomicVal, E);
4860 }
4861
Richard Smith11562c52011-10-28 17:51:58 +00004862 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004863 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004864 return StmtVisitorTy::Visit(E->getSubExpr());
4865
4866 case CK_LValueToRValue: {
4867 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004868 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4869 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004870 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004871 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004872 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004873 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004874 return false;
4875 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004876 }
4877 }
4878
Richard Smithf57d8cb2011-12-09 22:58:01 +00004879 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004880 }
4881
Aaron Ballman68af21c2014-01-03 19:26:43 +00004882 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004883 return VisitUnaryPostIncDec(UO);
4884 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004885 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004886 return VisitUnaryPostIncDec(UO);
4887 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004888 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004889 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004890 return Error(UO);
4891
4892 LValue LVal;
4893 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4894 return false;
4895 APValue RVal;
4896 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4897 UO->isIncrementOp(), &RVal))
4898 return false;
4899 return DerivedSuccess(RVal, UO);
4900 }
4901
Aaron Ballman68af21c2014-01-03 19:26:43 +00004902 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004903 // We will have checked the full-expressions inside the statement expression
4904 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004905 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004906 return Error(E);
4907
Richard Smith08d6a2c2013-07-24 07:11:57 +00004908 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004909 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004910 if (CS->body_empty())
4911 return true;
4912
Richard Smith51f03172013-06-20 03:00:05 +00004913 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4914 BE = CS->body_end();
4915 /**/; ++BI) {
4916 if (BI + 1 == BE) {
4917 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4918 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004919 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004920 diag::note_constexpr_stmt_expr_unsupported);
4921 return false;
4922 }
4923 return this->Visit(FinalExpr);
4924 }
4925
4926 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004927 StmtResult Result = { ReturnValue, nullptr };
4928 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004929 if (ESR != ESR_Succeeded) {
4930 // FIXME: If the statement-expression terminated due to 'return',
4931 // 'break', or 'continue', it would be nice to propagate that to
4932 // the outer statement evaluation rather than bailing out.
4933 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004934 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004935 diag::note_constexpr_stmt_expr_unsupported);
4936 return false;
4937 }
4938 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004939
4940 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004941 }
4942
Richard Smith4a678122011-10-24 18:44:57 +00004943 /// Visit a value which is evaluated, but whose value is ignored.
4944 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004945 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004946 }
David Majnemere9807b22016-02-26 04:23:19 +00004947
4948 /// Potentially visit a MemberExpr's base expression.
4949 void VisitIgnoredBaseExpression(const Expr *E) {
4950 // While MSVC doesn't evaluate the base expression, it does diagnose the
4951 // presence of side-effecting behavior.
4952 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4953 return;
4954 VisitIgnoredValue(E);
4955 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004956};
4957
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004958}
Peter Collingbournee9200682011-05-13 03:29:01 +00004959
4960//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004961// Common base class for lvalue and temporary evaluation.
4962//===----------------------------------------------------------------------===//
4963namespace {
4964template<class Derived>
4965class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004966 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004967protected:
4968 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00004969 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00004970 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004971 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004972
4973 bool Success(APValue::LValueBase B) {
4974 Result.set(B);
4975 return true;
4976 }
4977
George Burgess IVf9013bf2017-02-10 22:52:29 +00004978 bool evaluatePointer(const Expr *E, LValue &Result) {
4979 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4980 }
4981
Richard Smith027bf112011-11-17 22:56:20 +00004982public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004983 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4984 : ExprEvaluatorBaseTy(Info), Result(Result),
4985 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00004986
Richard Smith2e312c82012-03-03 22:46:17 +00004987 bool Success(const APValue &V, const Expr *E) {
4988 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004989 return true;
4990 }
Richard Smith027bf112011-11-17 22:56:20 +00004991
Richard Smith027bf112011-11-17 22:56:20 +00004992 bool VisitMemberExpr(const MemberExpr *E) {
4993 // Handle non-static data members.
4994 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004995 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004996 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004997 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00004998 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004999 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005000 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005001 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005002 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005003 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005004 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005005 BaseTy = E->getBase()->getType();
5006 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005007 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005008 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005009 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005010 Result.setInvalid(E);
5011 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005012 }
Richard Smith027bf112011-11-17 22:56:20 +00005013
Richard Smith1b78b3d2012-01-25 22:15:11 +00005014 const ValueDecl *MD = E->getMemberDecl();
5015 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5016 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5017 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5018 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005019 if (!HandleLValueMember(this->Info, E, Result, FD))
5020 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005021 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005022 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5023 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005024 } else
5025 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005026
Richard Smith1b78b3d2012-01-25 22:15:11 +00005027 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005028 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005029 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005030 RefValue))
5031 return false;
5032 return Success(RefValue, E);
5033 }
5034 return true;
5035 }
5036
5037 bool VisitBinaryOperator(const BinaryOperator *E) {
5038 switch (E->getOpcode()) {
5039 default:
5040 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5041
5042 case BO_PtrMemD:
5043 case BO_PtrMemI:
5044 return HandleMemberPointerAccess(this->Info, E, Result);
5045 }
5046 }
5047
5048 bool VisitCastExpr(const CastExpr *E) {
5049 switch (E->getCastKind()) {
5050 default:
5051 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5052
5053 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005054 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005055 if (!this->Visit(E->getSubExpr()))
5056 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005057
5058 // Now figure out the necessary offset to add to the base LV to get from
5059 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005060 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5061 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005062 }
5063 }
5064};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005065}
Richard Smith027bf112011-11-17 22:56:20 +00005066
5067//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005068// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005069//
5070// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5071// function designators (in C), decl references to void objects (in C), and
5072// temporaries (if building with -Wno-address-of-temporary).
5073//
5074// LValue evaluation produces values comprising a base expression of one of the
5075// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005076// - Declarations
5077// * VarDecl
5078// * FunctionDecl
5079// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005080// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005081// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005082// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005083// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005084// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005085// * ObjCEncodeExpr
5086// * AddrLabelExpr
5087// * BlockExpr
5088// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005089// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005090// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005091// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005092// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5093// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005094// * A MaterializeTemporaryExpr that has static storage duration, with no
5095// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005096// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005097//===----------------------------------------------------------------------===//
5098namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005099class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005100 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005101public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005102 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5103 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005104
Richard Smith11562c52011-10-28 17:51:58 +00005105 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005106 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005107
Peter Collingbournee9200682011-05-13 03:29:01 +00005108 bool VisitDeclRefExpr(const DeclRefExpr *E);
5109 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005110 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005111 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5112 bool VisitMemberExpr(const MemberExpr *E);
5113 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5114 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005115 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005116 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005117 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5118 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005119 bool VisitUnaryReal(const UnaryOperator *E);
5120 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005121 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5122 return VisitUnaryPreIncDec(UO);
5123 }
5124 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5125 return VisitUnaryPreIncDec(UO);
5126 }
Richard Smith3229b742013-05-05 21:17:10 +00005127 bool VisitBinAssign(const BinaryOperator *BO);
5128 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005129
Peter Collingbournee9200682011-05-13 03:29:01 +00005130 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005131 switch (E->getCastKind()) {
5132 default:
Richard Smith027bf112011-11-17 22:56:20 +00005133 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005134
Eli Friedmance3e02a2011-10-11 00:13:24 +00005135 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005136 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005137 if (!Visit(E->getSubExpr()))
5138 return false;
5139 Result.Designator.setInvalid();
5140 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005141
Richard Smith027bf112011-11-17 22:56:20 +00005142 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005143 if (!Visit(E->getSubExpr()))
5144 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005145 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005146 }
5147 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005148};
5149} // end anonymous namespace
5150
Richard Smith11562c52011-10-28 17:51:58 +00005151/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005152/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005153/// * function designators in C, and
5154/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005155/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005156static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5157 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005158 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005159 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005160 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005161}
5162
Peter Collingbournee9200682011-05-13 03:29:01 +00005163bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005164 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005165 return Success(FD);
5166 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005167 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005168 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005169 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005170 return Error(E);
5171}
Richard Smith733237d2011-10-24 23:14:33 +00005172
Faisal Vali0528a312016-11-13 06:09:16 +00005173
Richard Smith11562c52011-10-28 17:51:58 +00005174bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005175
5176 // If we are within a lambda's call operator, check whether the 'VD' referred
5177 // to within 'E' actually represents a lambda-capture that maps to a
5178 // data-member/field within the closure object, and if so, evaluate to the
5179 // field or what the field refers to.
5180 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5181 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5182 if (Info.checkingPotentialConstantExpression())
5183 return false;
5184 // Start with 'Result' referring to the complete closure object...
5185 Result = *Info.CurrentCall->This;
5186 // ... then update it to refer to the field of the closure object
5187 // that represents the capture.
5188 if (!HandleLValueMember(Info, E, Result, FD))
5189 return false;
5190 // And if the field is of reference type, update 'Result' to refer to what
5191 // the field refers to.
5192 if (FD->getType()->isReferenceType()) {
5193 APValue RVal;
5194 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5195 RVal))
5196 return false;
5197 Result.setFrom(Info.Ctx, RVal);
5198 }
5199 return true;
5200 }
5201 }
Craig Topper36250ad2014-05-12 05:36:57 +00005202 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005203 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5204 // Only if a local variable was declared in the function currently being
5205 // evaluated, do we expect to be able to find its value in the current
5206 // frame. (Otherwise it was likely declared in an enclosing context and
5207 // could either have a valid evaluatable value (for e.g. a constexpr
5208 // variable) or be ill-formed (and trigger an appropriate evaluation
5209 // diagnostic)).
5210 if (Info.CurrentCall->Callee &&
5211 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5212 Frame = Info.CurrentCall;
5213 }
5214 }
Richard Smith3229b742013-05-05 21:17:10 +00005215
Richard Smithfec09922011-11-01 16:57:24 +00005216 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005217 if (Frame) {
5218 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005219 return true;
5220 }
Richard Smithce40ad62011-11-12 22:28:03 +00005221 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005222 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005223
Richard Smith3229b742013-05-05 21:17:10 +00005224 APValue *V;
5225 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005226 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005227 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005228 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005229 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005230 return false;
5231 }
Richard Smith3229b742013-05-05 21:17:10 +00005232 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005233}
5234
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005235bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5236 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005237 // Walk through the expression to find the materialized temporary itself.
5238 SmallVector<const Expr *, 2> CommaLHSs;
5239 SmallVector<SubobjectAdjustment, 2> Adjustments;
5240 const Expr *Inner = E->GetTemporaryExpr()->
5241 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005242
Richard Smith84401042013-06-03 05:03:02 +00005243 // If we passed any comma operators, evaluate their LHSs.
5244 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5245 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5246 return false;
5247
Richard Smithe6c01442013-06-05 00:46:14 +00005248 // A materialized temporary with static storage duration can appear within the
5249 // result of a constant expression evaluation, so we need to preserve its
5250 // value for use outside this evaluation.
5251 APValue *Value;
5252 if (E->getStorageDuration() == SD_Static) {
5253 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005254 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005255 Result.set(E);
5256 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005257 Value = &Info.CurrentCall->
5258 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005259 Result.set(E, Info.CurrentCall->Index);
5260 }
5261
Richard Smithea4ad5d2013-06-06 08:19:16 +00005262 QualType Type = Inner->getType();
5263
Richard Smith84401042013-06-03 05:03:02 +00005264 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005265 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5266 (E->getStorageDuration() == SD_Static &&
5267 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5268 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005269 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005270 }
Richard Smith84401042013-06-03 05:03:02 +00005271
5272 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005273 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5274 --I;
5275 switch (Adjustments[I].Kind) {
5276 case SubobjectAdjustment::DerivedToBaseAdjustment:
5277 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5278 Type, Result))
5279 return false;
5280 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5281 break;
5282
5283 case SubobjectAdjustment::FieldAdjustment:
5284 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5285 return false;
5286 Type = Adjustments[I].Field->getType();
5287 break;
5288
5289 case SubobjectAdjustment::MemberPointerAdjustment:
5290 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5291 Adjustments[I].Ptr.RHS))
5292 return false;
5293 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5294 break;
5295 }
5296 }
5297
5298 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005299}
5300
Peter Collingbournee9200682011-05-13 03:29:01 +00005301bool
5302LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005303 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5304 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005305 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5306 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005307 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005308}
5309
Richard Smith6e525142011-12-27 12:18:28 +00005310bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005311 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005312 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005313
Faisal Valie690b7a2016-07-02 22:34:24 +00005314 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005315 << E->getExprOperand()->getType()
5316 << E->getExprOperand()->getSourceRange();
5317 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005318}
5319
Francois Pichet0066db92012-04-16 04:08:35 +00005320bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5321 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005322}
Francois Pichet0066db92012-04-16 04:08:35 +00005323
Peter Collingbournee9200682011-05-13 03:29:01 +00005324bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005325 // Handle static data members.
5326 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005327 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005328 return VisitVarDecl(E, VD);
5329 }
5330
Richard Smith254a73d2011-10-28 22:34:42 +00005331 // Handle static member functions.
5332 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5333 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005334 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005335 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005336 }
5337 }
5338
Richard Smithd62306a2011-11-10 06:34:14 +00005339 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005340 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005341}
5342
Peter Collingbournee9200682011-05-13 03:29:01 +00005343bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005344 // FIXME: Deal with vectors as array subscript bases.
5345 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005346 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005347
Nick Lewyckyad888682017-04-27 07:27:36 +00005348 bool Success = true;
5349 if (!evaluatePointer(E->getBase(), Result)) {
5350 if (!Info.noteFailure())
5351 return false;
5352 Success = false;
5353 }
Mike Stump11289f42009-09-09 15:08:12 +00005354
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005355 APSInt Index;
5356 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005357 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005358
Nick Lewyckyad888682017-04-27 07:27:36 +00005359 return Success &&
5360 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005361}
Eli Friedman9a156e52008-11-12 09:44:48 +00005362
Peter Collingbournee9200682011-05-13 03:29:01 +00005363bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005364 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005365}
5366
Richard Smith66c96992012-02-18 22:04:06 +00005367bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5368 if (!Visit(E->getSubExpr()))
5369 return false;
5370 // __real is a no-op on scalar lvalues.
5371 if (E->getSubExpr()->getType()->isAnyComplexType())
5372 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5373 return true;
5374}
5375
5376bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5377 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5378 "lvalue __imag__ on scalar?");
5379 if (!Visit(E->getSubExpr()))
5380 return false;
5381 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5382 return true;
5383}
5384
Richard Smith243ef902013-05-05 23:31:59 +00005385bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005386 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005387 return Error(UO);
5388
5389 if (!this->Visit(UO->getSubExpr()))
5390 return false;
5391
Richard Smith243ef902013-05-05 23:31:59 +00005392 return handleIncDec(
5393 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005394 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005395}
5396
5397bool LValueExprEvaluator::VisitCompoundAssignOperator(
5398 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005399 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005400 return Error(CAO);
5401
Richard Smith3229b742013-05-05 21:17:10 +00005402 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005403
5404 // The overall lvalue result is the result of evaluating the LHS.
5405 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005406 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005407 Evaluate(RHS, this->Info, CAO->getRHS());
5408 return false;
5409 }
5410
Richard Smith3229b742013-05-05 21:17:10 +00005411 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5412 return false;
5413
Richard Smith43e77732013-05-07 04:50:00 +00005414 return handleCompoundAssignment(
5415 this->Info, CAO,
5416 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5417 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005418}
5419
5420bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005421 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005422 return Error(E);
5423
Richard Smith3229b742013-05-05 21:17:10 +00005424 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005425
5426 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005427 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005428 Evaluate(NewVal, this->Info, E->getRHS());
5429 return false;
5430 }
5431
Richard Smith3229b742013-05-05 21:17:10 +00005432 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5433 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005434
5435 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005436 NewVal);
5437}
5438
Eli Friedman9a156e52008-11-12 09:44:48 +00005439//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005440// Pointer Evaluation
5441//===----------------------------------------------------------------------===//
5442
George Burgess IVe3763372016-12-22 02:50:20 +00005443/// \brief Attempts to compute the number of bytes available at the pointer
5444/// returned by a function with the alloc_size attribute. Returns true if we
5445/// were successful. Places an unsigned number into `Result`.
5446///
5447/// This expects the given CallExpr to be a call to a function with an
5448/// alloc_size attribute.
5449static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5450 const CallExpr *Call,
5451 llvm::APInt &Result) {
5452 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5453
5454 // alloc_size args are 1-indexed, 0 means not present.
5455 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5456 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5457 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5458 if (Call->getNumArgs() <= SizeArgNo)
5459 return false;
5460
5461 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5462 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5463 return false;
5464 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5465 return false;
5466 Into = Into.zextOrSelf(BitsInSizeT);
5467 return true;
5468 };
5469
5470 APSInt SizeOfElem;
5471 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5472 return false;
5473
5474 if (!AllocSize->getNumElemsParam()) {
5475 Result = std::move(SizeOfElem);
5476 return true;
5477 }
5478
5479 APSInt NumberOfElems;
5480 // Argument numbers start at 1
5481 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5482 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5483 return false;
5484
5485 bool Overflow;
5486 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5487 if (Overflow)
5488 return false;
5489
5490 Result = std::move(BytesAvailable);
5491 return true;
5492}
5493
5494/// \brief Convenience function. LVal's base must be a call to an alloc_size
5495/// function.
5496static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5497 const LValue &LVal,
5498 llvm::APInt &Result) {
5499 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5500 "Can't get the size of a non alloc_size function");
5501 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5502 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5503 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5504}
5505
5506/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5507/// a function with the alloc_size attribute. If it was possible to do so, this
5508/// function will return true, make Result's Base point to said function call,
5509/// and mark Result's Base as invalid.
5510static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5511 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005512 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005513 return false;
5514
5515 // Because we do no form of static analysis, we only support const variables.
5516 //
5517 // Additionally, we can't support parameters, nor can we support static
5518 // variables (in the latter case, use-before-assign isn't UB; in the former,
5519 // we have no clue what they'll be assigned to).
5520 const auto *VD =
5521 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5522 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5523 return false;
5524
5525 const Expr *Init = VD->getAnyInitializer();
5526 if (!Init)
5527 return false;
5528
5529 const Expr *E = Init->IgnoreParens();
5530 if (!tryUnwrapAllocSizeCall(E))
5531 return false;
5532
5533 // Store E instead of E unwrapped so that the type of the LValue's base is
5534 // what the user wanted.
5535 Result.setInvalid(E);
5536
5537 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005538 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005539 return true;
5540}
5541
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005542namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005543class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005544 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005545 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005546 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005547
Peter Collingbournee9200682011-05-13 03:29:01 +00005548 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005549 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005550 return true;
5551 }
George Burgess IVe3763372016-12-22 02:50:20 +00005552
George Burgess IVf9013bf2017-02-10 22:52:29 +00005553 bool evaluateLValue(const Expr *E, LValue &Result) {
5554 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5555 }
5556
5557 bool evaluatePointer(const Expr *E, LValue &Result) {
5558 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5559 }
5560
George Burgess IVe3763372016-12-22 02:50:20 +00005561 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005562public:
Mike Stump11289f42009-09-09 15:08:12 +00005563
George Burgess IVf9013bf2017-02-10 22:52:29 +00005564 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5565 : ExprEvaluatorBaseTy(info), Result(Result),
5566 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005567
Richard Smith2e312c82012-03-03 22:46:17 +00005568 bool Success(const APValue &V, const Expr *E) {
5569 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005570 return true;
5571 }
Richard Smithfddd3842011-12-30 21:15:51 +00005572 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005573 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5574 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005575 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005576 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005577
John McCall45d55e42010-05-07 21:00:08 +00005578 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005579 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005580 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005581 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005582 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005583 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5584 if (Info.noteFailure())
5585 EvaluateIgnoredValue(Info, E->getSubExpr());
5586 return Error(E);
5587 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005588 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005589 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005590 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005591 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005592 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005593 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005594 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005595 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005596 }
Richard Smithd62306a2011-11-10 06:34:14 +00005597 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005598 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005599 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005600 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005601 if (!Info.CurrentCall->This) {
5602 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005603 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005604 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005605 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005606 return false;
5607 }
Richard Smithd62306a2011-11-10 06:34:14 +00005608 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005609 // If we are inside a lambda's call operator, the 'this' expression refers
5610 // to the enclosing '*this' object (either by value or reference) which is
5611 // either copied into the closure object's field that represents the '*this'
5612 // or refers to '*this'.
5613 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5614 // Update 'Result' to refer to the data member/field of the closure object
5615 // that represents the '*this' capture.
5616 if (!HandleLValueMember(Info, E, Result,
Daniel Jasperffdee092017-05-02 19:21:42 +00005617 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005618 return false;
5619 // If we captured '*this' by reference, replace the field with its referent.
5620 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5621 ->isPointerType()) {
5622 APValue RVal;
5623 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5624 RVal))
5625 return false;
5626
5627 Result.setFrom(Info.Ctx, RVal);
5628 }
5629 }
Richard Smithd62306a2011-11-10 06:34:14 +00005630 return true;
5631 }
John McCallc07a0c72011-02-17 10:25:35 +00005632
Eli Friedman449fe542009-03-23 04:56:01 +00005633 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005634};
Chris Lattner05706e882008-07-11 18:11:29 +00005635} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005636
George Burgess IVf9013bf2017-02-10 22:52:29 +00005637static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5638 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005639 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005640 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005641}
5642
John McCall45d55e42010-05-07 21:00:08 +00005643bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005644 if (E->getOpcode() != BO_Add &&
5645 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005646 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005647
Chris Lattner05706e882008-07-11 18:11:29 +00005648 const Expr *PExp = E->getLHS();
5649 const Expr *IExp = E->getRHS();
5650 if (IExp->getType()->isPointerType())
5651 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005652
George Burgess IVf9013bf2017-02-10 22:52:29 +00005653 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005654 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005655 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005656
John McCall45d55e42010-05-07 21:00:08 +00005657 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005658 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005659 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005660
Richard Smith96e0c102011-11-04 02:25:55 +00005661 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005662 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005663
Ted Kremenek28831752012-08-23 20:46:57 +00005664 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005665 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005666}
Eli Friedman9a156e52008-11-12 09:44:48 +00005667
John McCall45d55e42010-05-07 21:00:08 +00005668bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005669 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005670}
Mike Stump11289f42009-09-09 15:08:12 +00005671
Peter Collingbournee9200682011-05-13 03:29:01 +00005672bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5673 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005674
Eli Friedman847a2bc2009-12-27 05:43:15 +00005675 switch (E->getCastKind()) {
5676 default:
5677 break;
5678
John McCalle3027922010-08-25 11:45:40 +00005679 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005680 case CK_CPointerToObjCPointerCast:
5681 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005682 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005683 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005684 if (!Visit(SubExpr))
5685 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005686 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5687 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5688 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005689 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005690 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005691 if (SubExpr->getType()->isVoidPointerType())
5692 CCEDiag(E, diag::note_constexpr_invalid_cast)
5693 << 3 << SubExpr->getType();
5694 else
5695 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5696 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005697 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5698 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005699 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005700
Anders Carlsson18275092010-10-31 20:41:46 +00005701 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005702 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005703 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005704 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005705 if (!Result.Base && Result.Offset.isZero())
5706 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005707
Richard Smithd62306a2011-11-10 06:34:14 +00005708 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005709 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005710 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5711 castAs<PointerType>()->getPointeeType(),
5712 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005713
Richard Smith027bf112011-11-17 22:56:20 +00005714 case CK_BaseToDerived:
5715 if (!Visit(E->getSubExpr()))
5716 return false;
5717 if (!Result.Base && Result.Offset.isZero())
5718 return true;
5719 return HandleBaseToDerivedCast(Info, E, Result);
5720
Richard Smith0b0a0b62011-10-29 20:57:55 +00005721 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005722 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005723 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005724
John McCalle3027922010-08-25 11:45:40 +00005725 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005726 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5727
Richard Smith2e312c82012-03-03 22:46:17 +00005728 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005729 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005730 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005731
John McCall45d55e42010-05-07 21:00:08 +00005732 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005733 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5734 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005735 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005736 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005737 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005738 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005739 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005740 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005741 return true;
5742 } else {
5743 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005744 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005745 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005746 }
5747 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005748
5749 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005750 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005751 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005752 return false;
5753 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005754 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005755 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005756 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005757 return false;
5758 }
Richard Smith96e0c102011-11-04 02:25:55 +00005759 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005760 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5761 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005762 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005763 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005764 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005765 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005766 }
Richard Smithdd785442011-10-31 20:57:44 +00005767
John McCalle3027922010-08-25 11:45:40 +00005768 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005769 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005770
5771 case CK_LValueToRValue: {
5772 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005773 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005774 return false;
5775
5776 APValue RVal;
5777 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5778 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5779 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005780 return InvalidBaseOK &&
5781 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005782 return Success(RVal, E);
5783 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005784 }
5785
Richard Smith11562c52011-10-28 17:51:58 +00005786 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005787}
Chris Lattner05706e882008-07-11 18:11:29 +00005788
Hal Finkel0dd05d42014-10-03 17:18:37 +00005789static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5790 // C++ [expr.alignof]p3:
5791 // When alignof is applied to a reference type, the result is the
5792 // alignment of the referenced type.
5793 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5794 T = Ref->getPointeeType();
5795
5796 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005797 if (T.getQualifiers().hasUnaligned())
5798 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005799 return Info.Ctx.toCharUnitsFromBits(
5800 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5801}
5802
5803static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5804 E = E->IgnoreParens();
5805
5806 // The kinds of expressions that we have special-case logic here for
5807 // should be kept up to date with the special checks for those
5808 // expressions in Sema.
5809
5810 // alignof decl is always accepted, even if it doesn't make sense: we default
5811 // to 1 in those cases.
5812 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5813 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5814 /*RefAsPointee*/true);
5815
5816 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5817 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5818 /*RefAsPointee*/true);
5819
5820 return GetAlignOfType(Info, E->getType());
5821}
5822
George Burgess IVe3763372016-12-22 02:50:20 +00005823// To be clear: this happily visits unsupported builtins. Better name welcomed.
5824bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5825 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5826 return true;
5827
George Burgess IVf9013bf2017-02-10 22:52:29 +00005828 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005829 return false;
5830
5831 Result.setInvalid(E);
5832 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005833 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00005834 return true;
5835}
5836
Peter Collingbournee9200682011-05-13 03:29:01 +00005837bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005838 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005839 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005840
Richard Smith6328cbd2016-11-16 00:57:23 +00005841 if (unsigned BuiltinOp = E->getBuiltinCallee())
5842 return VisitBuiltinCallExpr(E, BuiltinOp);
5843
George Burgess IVe3763372016-12-22 02:50:20 +00005844 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005845}
5846
5847bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5848 unsigned BuiltinOp) {
5849 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005850 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005851 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005852 case Builtin::BI__builtin_assume_aligned: {
5853 // We need to be very careful here because: if the pointer does not have the
5854 // asserted alignment, then the behavior is undefined, and undefined
5855 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005856 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005857 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005858
Hal Finkel0dd05d42014-10-03 17:18:37 +00005859 LValue OffsetResult(Result);
5860 APSInt Alignment;
5861 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5862 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005863 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005864
5865 if (E->getNumArgs() > 2) {
5866 APSInt Offset;
5867 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5868 return false;
5869
Richard Smith642a2362017-01-30 23:30:26 +00005870 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005871 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5872 }
5873
5874 // If there is a base object, then it must have the correct alignment.
5875 if (OffsetResult.Base) {
5876 CharUnits BaseAlignment;
5877 if (const ValueDecl *VD =
5878 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5879 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5880 } else {
5881 BaseAlignment =
5882 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5883 }
5884
5885 if (BaseAlignment < Align) {
5886 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005887 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005888 CCEDiag(E->getArg(0),
5889 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005890 << (unsigned)BaseAlignment.getQuantity()
5891 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005892 return false;
5893 }
5894 }
5895
5896 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005897 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005898 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005899
Richard Smith642a2362017-01-30 23:30:26 +00005900 (OffsetResult.Base
5901 ? CCEDiag(E->getArg(0),
5902 diag::note_constexpr_baa_insufficient_alignment) << 1
5903 : CCEDiag(E->getArg(0),
5904 diag::note_constexpr_baa_value_insufficient_alignment))
5905 << (int)OffsetResult.Offset.getQuantity()
5906 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005907 return false;
5908 }
5909
5910 return true;
5911 }
Richard Smithe9507952016-11-12 01:39:56 +00005912
5913 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005914 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005915 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005916 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005917 if (Info.getLangOpts().CPlusPlus11)
5918 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5919 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005920 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005921 else
5922 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005923 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00005924 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005925 case Builtin::BI__builtin_wcschr:
5926 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005927 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005928 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005929 if (!Visit(E->getArg(0)))
5930 return false;
5931 APSInt Desired;
5932 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5933 return false;
5934 uint64_t MaxLength = uint64_t(-1);
5935 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005936 BuiltinOp != Builtin::BIwcschr &&
5937 BuiltinOp != Builtin::BI__builtin_strchr &&
5938 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005939 APSInt N;
5940 if (!EvaluateInteger(E->getArg(2), N, Info))
5941 return false;
5942 MaxLength = N.getExtValue();
5943 }
5944
Richard Smith8110c9d2016-11-29 19:45:17 +00005945 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005946
Richard Smith8110c9d2016-11-29 19:45:17 +00005947 // Figure out what value we're actually looking for (after converting to
5948 // the corresponding unsigned type if necessary).
5949 uint64_t DesiredVal;
5950 bool StopAtNull = false;
5951 switch (BuiltinOp) {
5952 case Builtin::BIstrchr:
5953 case Builtin::BI__builtin_strchr:
5954 // strchr compares directly to the passed integer, and therefore
5955 // always fails if given an int that is not a char.
5956 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5957 E->getArg(1)->getType(),
5958 Desired),
5959 Desired))
5960 return ZeroInitialization(E);
5961 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005962 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00005963 case Builtin::BImemchr:
5964 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005965 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005966 // memchr compares by converting both sides to unsigned char. That's also
5967 // correct for strchr if we get this far (to cope with plain char being
5968 // unsigned in the strchr case).
5969 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5970 break;
Richard Smithe9507952016-11-12 01:39:56 +00005971
Richard Smith8110c9d2016-11-29 19:45:17 +00005972 case Builtin::BIwcschr:
5973 case Builtin::BI__builtin_wcschr:
5974 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005975 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00005976 case Builtin::BIwmemchr:
5977 case Builtin::BI__builtin_wmemchr:
5978 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5979 DesiredVal = Desired.getZExtValue();
5980 break;
5981 }
Richard Smithe9507952016-11-12 01:39:56 +00005982
5983 for (; MaxLength; --MaxLength) {
5984 APValue Char;
5985 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5986 !Char.isInt())
5987 return false;
5988 if (Char.getInt().getZExtValue() == DesiredVal)
5989 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005990 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005991 break;
5992 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5993 return false;
5994 }
5995 // Not found: return nullptr.
5996 return ZeroInitialization(E);
5997 }
5998
Richard Smith6cbd65d2013-07-11 02:27:57 +00005999 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006000 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006001 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006002}
Chris Lattner05706e882008-07-11 18:11:29 +00006003
6004//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006005// Member Pointer Evaluation
6006//===----------------------------------------------------------------------===//
6007
6008namespace {
6009class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006010 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006011 MemberPtr &Result;
6012
6013 bool Success(const ValueDecl *D) {
6014 Result = MemberPtr(D);
6015 return true;
6016 }
6017public:
6018
6019 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6020 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6021
Richard Smith2e312c82012-03-03 22:46:17 +00006022 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006023 Result.setFrom(V);
6024 return true;
6025 }
Richard Smithfddd3842011-12-30 21:15:51 +00006026 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006027 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006028 }
6029
6030 bool VisitCastExpr(const CastExpr *E);
6031 bool VisitUnaryAddrOf(const UnaryOperator *E);
6032};
6033} // end anonymous namespace
6034
6035static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6036 EvalInfo &Info) {
6037 assert(E->isRValue() && E->getType()->isMemberPointerType());
6038 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6039}
6040
6041bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6042 switch (E->getCastKind()) {
6043 default:
6044 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6045
6046 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006047 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006048 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006049
6050 case CK_BaseToDerivedMemberPointer: {
6051 if (!Visit(E->getSubExpr()))
6052 return false;
6053 if (E->path_empty())
6054 return true;
6055 // Base-to-derived member pointer casts store the path in derived-to-base
6056 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6057 // the wrong end of the derived->base arc, so stagger the path by one class.
6058 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6059 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6060 PathI != PathE; ++PathI) {
6061 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6062 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6063 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006064 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006065 }
6066 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6067 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006068 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006069 return true;
6070 }
6071
6072 case CK_DerivedToBaseMemberPointer:
6073 if (!Visit(E->getSubExpr()))
6074 return false;
6075 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6076 PathE = E->path_end(); PathI != PathE; ++PathI) {
6077 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6078 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6079 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006080 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006081 }
6082 return true;
6083 }
6084}
6085
6086bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6087 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6088 // member can be formed.
6089 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6090}
6091
6092//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006093// Record Evaluation
6094//===----------------------------------------------------------------------===//
6095
6096namespace {
6097 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006098 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006099 const LValue &This;
6100 APValue &Result;
6101 public:
6102
6103 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6104 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6105
Richard Smith2e312c82012-03-03 22:46:17 +00006106 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006107 Result = V;
6108 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006109 }
Richard Smithb8348f52016-05-12 22:16:28 +00006110 bool ZeroInitialization(const Expr *E) {
6111 return ZeroInitialization(E, E->getType());
6112 }
6113 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006114
Richard Smith52a980a2015-08-28 02:43:42 +00006115 bool VisitCallExpr(const CallExpr *E) {
6116 return handleCallExpr(E, Result, &This);
6117 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006118 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006119 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006120 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6121 return VisitCXXConstructExpr(E, E->getType());
6122 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006123 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006124 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006125 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006126 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006127 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006128}
Richard Smithd62306a2011-11-10 06:34:14 +00006129
Richard Smithfddd3842011-12-30 21:15:51 +00006130/// Perform zero-initialization on an object of non-union class type.
6131/// C++11 [dcl.init]p5:
6132/// To zero-initialize an object or reference of type T means:
6133/// [...]
6134/// -- if T is a (possibly cv-qualified) non-union class type,
6135/// each non-static data member and each base-class subobject is
6136/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006137static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6138 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006139 const LValue &This, APValue &Result) {
6140 assert(!RD->isUnion() && "Expected non-union class type");
6141 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6142 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006143 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006144
John McCalld7bca762012-05-01 00:38:49 +00006145 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006146 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6147
6148 if (CD) {
6149 unsigned Index = 0;
6150 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006151 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006152 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6153 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006154 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6155 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006156 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006157 Result.getStructBase(Index)))
6158 return false;
6159 }
6160 }
6161
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006162 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006163 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006164 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006165 continue;
6166
6167 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006168 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006169 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006170
David Blaikie2d7c57e2012-04-30 02:36:29 +00006171 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006172 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006173 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006174 return false;
6175 }
6176
6177 return true;
6178}
6179
Richard Smithb8348f52016-05-12 22:16:28 +00006180bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6181 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006182 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006183 if (RD->isUnion()) {
6184 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6185 // object's first non-static named data member is zero-initialized
6186 RecordDecl::field_iterator I = RD->field_begin();
6187 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006188 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006189 return true;
6190 }
6191
6192 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006193 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006194 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006195 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006196 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006197 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006198 }
6199
Richard Smith5d108602012-02-17 00:44:16 +00006200 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006201 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006202 return false;
6203 }
6204
Richard Smitha8105bc2012-01-06 16:39:00 +00006205 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006206}
6207
Richard Smithe97cbd72011-11-11 04:05:33 +00006208bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6209 switch (E->getCastKind()) {
6210 default:
6211 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6212
6213 case CK_ConstructorConversion:
6214 return Visit(E->getSubExpr());
6215
6216 case CK_DerivedToBase:
6217 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006218 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006219 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006220 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006221 if (!DerivedObject.isStruct())
6222 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006223
6224 // Derived-to-base rvalue conversion: just slice off the derived part.
6225 APValue *Value = &DerivedObject;
6226 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6227 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6228 PathE = E->path_end(); PathI != PathE; ++PathI) {
6229 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6230 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6231 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6232 RD = Base;
6233 }
6234 Result = *Value;
6235 return true;
6236 }
6237 }
6238}
6239
Richard Smithd62306a2011-11-10 06:34:14 +00006240bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006241 if (E->isTransparent())
6242 return Visit(E->getInit(0));
6243
Richard Smithd62306a2011-11-10 06:34:14 +00006244 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006245 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006246 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6247
6248 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006249 const FieldDecl *Field = E->getInitializedFieldInUnion();
6250 Result = APValue(Field);
6251 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006252 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006253
6254 // If the initializer list for a union does not contain any elements, the
6255 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006256 // FIXME: The element should be initialized from an initializer list.
6257 // Is this difference ever observable for initializer lists which
6258 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006259 ImplicitValueInitExpr VIE(Field->getType());
6260 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6261
Richard Smithd62306a2011-11-10 06:34:14 +00006262 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006263 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6264 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006265
6266 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6267 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6268 isa<CXXDefaultInitExpr>(InitExpr));
6269
Richard Smithb228a862012-02-15 02:18:13 +00006270 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006271 }
6272
Richard Smith872307e2016-03-08 22:17:41 +00006273 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006274 if (Result.isUninit())
6275 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6276 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006277 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006278 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006279
6280 // Initialize base classes.
6281 if (CXXRD) {
6282 for (const auto &Base : CXXRD->bases()) {
6283 assert(ElementNo < E->getNumInits() && "missing init for base class");
6284 const Expr *Init = E->getInit(ElementNo);
6285
6286 LValue Subobject = This;
6287 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6288 return false;
6289
6290 APValue &FieldVal = Result.getStructBase(ElementNo);
6291 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006292 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006293 return false;
6294 Success = false;
6295 }
6296 ++ElementNo;
6297 }
6298 }
6299
6300 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006301 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006302 // Anonymous bit-fields are not considered members of the class for
6303 // purposes of aggregate initialization.
6304 if (Field->isUnnamedBitfield())
6305 continue;
6306
6307 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006308
Richard Smith253c2a32012-01-27 01:14:48 +00006309 bool HaveInit = ElementNo < E->getNumInits();
6310
6311 // FIXME: Diagnostics here should point to the end of the initializer
6312 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006313 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006314 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006315 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006316
6317 // Perform an implicit value-initialization for members beyond the end of
6318 // the initializer list.
6319 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006320 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006321
Richard Smith852c9db2013-04-20 22:23:05 +00006322 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6323 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6324 isa<CXXDefaultInitExpr>(Init));
6325
Richard Smith49ca8aa2013-08-06 07:09:20 +00006326 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6327 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6328 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006329 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006330 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006331 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006332 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006333 }
6334 }
6335
Richard Smith253c2a32012-01-27 01:14:48 +00006336 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006337}
6338
Richard Smithb8348f52016-05-12 22:16:28 +00006339bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6340 QualType T) {
6341 // Note that E's type is not necessarily the type of our class here; we might
6342 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006343 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006344 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6345
Richard Smithfddd3842011-12-30 21:15:51 +00006346 bool ZeroInit = E->requiresZeroInitialization();
6347 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006348 // If we've already performed zero-initialization, we're already done.
6349 if (!Result.isUninit())
6350 return true;
6351
Richard Smithda3f4fd2014-03-05 23:32:50 +00006352 // We can get here in two different ways:
6353 // 1) We're performing value-initialization, and should zero-initialize
6354 // the object, or
6355 // 2) We're performing default-initialization of an object with a trivial
6356 // constexpr default constructor, in which case we should start the
6357 // lifetimes of all the base subobjects (there can be no data member
6358 // subobjects in this case) per [basic.life]p1.
6359 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006360 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006361 }
6362
Craig Topper36250ad2014-05-12 05:36:57 +00006363 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006364 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006365
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006366 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006367 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006368
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006369 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006370 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006371 if (const MaterializeTemporaryExpr *ME
6372 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6373 return Visit(ME->GetTemporaryExpr());
6374
Richard Smithb8348f52016-05-12 22:16:28 +00006375 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006376 return false;
6377
Craig Topper5fc8fc22014-08-27 06:28:36 +00006378 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006379 return HandleConstructorCall(E, This, Args,
6380 cast<CXXConstructorDecl>(Definition), Info,
6381 Result);
6382}
6383
6384bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6385 const CXXInheritedCtorInitExpr *E) {
6386 if (!Info.CurrentCall) {
6387 assert(Info.checkingPotentialConstantExpression());
6388 return false;
6389 }
6390
6391 const CXXConstructorDecl *FD = E->getConstructor();
6392 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6393 return false;
6394
6395 const FunctionDecl *Definition = nullptr;
6396 auto Body = FD->getBody(Definition);
6397
6398 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6399 return false;
6400
6401 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006402 cast<CXXConstructorDecl>(Definition), Info,
6403 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006404}
6405
Richard Smithcc1b96d2013-06-12 22:31:48 +00006406bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6407 const CXXStdInitializerListExpr *E) {
6408 const ConstantArrayType *ArrayType =
6409 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6410
6411 LValue Array;
6412 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6413 return false;
6414
6415 // Get a pointer to the first element of the array.
6416 Array.addArray(Info, E, ArrayType);
6417
6418 // FIXME: Perform the checks on the field types in SemaInit.
6419 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6420 RecordDecl::field_iterator Field = Record->field_begin();
6421 if (Field == Record->field_end())
6422 return Error(E);
6423
6424 // Start pointer.
6425 if (!Field->getType()->isPointerType() ||
6426 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6427 ArrayType->getElementType()))
6428 return Error(E);
6429
6430 // FIXME: What if the initializer_list type has base classes, etc?
6431 Result = APValue(APValue::UninitStruct(), 0, 2);
6432 Array.moveInto(Result.getStructField(0));
6433
6434 if (++Field == Record->field_end())
6435 return Error(E);
6436
6437 if (Field->getType()->isPointerType() &&
6438 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6439 ArrayType->getElementType())) {
6440 // End pointer.
6441 if (!HandleLValueArrayAdjustment(Info, E, Array,
6442 ArrayType->getElementType(),
6443 ArrayType->getSize().getZExtValue()))
6444 return false;
6445 Array.moveInto(Result.getStructField(1));
6446 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6447 // Length.
6448 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6449 else
6450 return Error(E);
6451
6452 if (++Field != Record->field_end())
6453 return Error(E);
6454
6455 return true;
6456}
6457
Faisal Valic72a08c2017-01-09 03:02:53 +00006458bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6459 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6460 if (ClosureClass->isInvalidDecl()) return false;
6461
6462 if (Info.checkingPotentialConstantExpression()) return true;
Daniel Jasperffdee092017-05-02 19:21:42 +00006463
Faisal Vali051e3a22017-02-16 04:12:21 +00006464 const size_t NumFields =
6465 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006466
6467 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6468 E->capture_init_end()) &&
6469 "The number of lambda capture initializers should equal the number of "
6470 "fields within the closure type");
6471
Faisal Vali051e3a22017-02-16 04:12:21 +00006472 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6473 // Iterate through all the lambda's closure object's fields and initialize
6474 // them.
6475 auto *CaptureInitIt = E->capture_init_begin();
6476 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6477 bool Success = true;
6478 for (const auto *Field : ClosureClass->fields()) {
6479 assert(CaptureInitIt != E->capture_init_end());
6480 // Get the initializer for this field
6481 Expr *const CurFieldInit = *CaptureInitIt++;
Daniel Jasperffdee092017-05-02 19:21:42 +00006482
Faisal Vali051e3a22017-02-16 04:12:21 +00006483 // If there is no initializer, either this is a VLA or an error has
6484 // occurred.
6485 if (!CurFieldInit)
6486 return Error(E);
6487
6488 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6489 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6490 if (!Info.keepEvaluatingAfterFailure())
6491 return false;
6492 Success = false;
6493 }
6494 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006495 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006496 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006497}
6498
Richard Smithd62306a2011-11-10 06:34:14 +00006499static bool EvaluateRecord(const Expr *E, const LValue &This,
6500 APValue &Result, EvalInfo &Info) {
6501 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006502 "can't evaluate expression as a record rvalue");
6503 return RecordExprEvaluator(Info, This, Result).Visit(E);
6504}
6505
6506//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006507// Temporary Evaluation
6508//
6509// Temporaries are represented in the AST as rvalues, but generally behave like
6510// lvalues. The full-object of which the temporary is a subobject is implicitly
6511// materialized so that a reference can bind to it.
6512//===----------------------------------------------------------------------===//
6513namespace {
6514class TemporaryExprEvaluator
6515 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6516public:
6517 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006518 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006519
6520 /// Visit an expression which constructs the value of this temporary.
6521 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006522 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006523 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6524 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006525 }
6526
6527 bool VisitCastExpr(const CastExpr *E) {
6528 switch (E->getCastKind()) {
6529 default:
6530 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6531
6532 case CK_ConstructorConversion:
6533 return VisitConstructExpr(E->getSubExpr());
6534 }
6535 }
6536 bool VisitInitListExpr(const InitListExpr *E) {
6537 return VisitConstructExpr(E);
6538 }
6539 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6540 return VisitConstructExpr(E);
6541 }
6542 bool VisitCallExpr(const CallExpr *E) {
6543 return VisitConstructExpr(E);
6544 }
Richard Smith513955c2014-12-17 19:24:30 +00006545 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6546 return VisitConstructExpr(E);
6547 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006548 bool VisitLambdaExpr(const LambdaExpr *E) {
6549 return VisitConstructExpr(E);
6550 }
Richard Smith027bf112011-11-17 22:56:20 +00006551};
6552} // end anonymous namespace
6553
6554/// Evaluate an expression of record type as a temporary.
6555static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006556 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006557 return TemporaryExprEvaluator(Info, Result).Visit(E);
6558}
6559
6560//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006561// Vector Evaluation
6562//===----------------------------------------------------------------------===//
6563
6564namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006565 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006566 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006567 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006568 public:
Mike Stump11289f42009-09-09 15:08:12 +00006569
Richard Smith2d406342011-10-22 21:10:00 +00006570 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6571 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006572
Craig Topper9798b932015-09-29 04:30:05 +00006573 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006574 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6575 // FIXME: remove this APValue copy.
6576 Result = APValue(V.data(), V.size());
6577 return true;
6578 }
Richard Smith2e312c82012-03-03 22:46:17 +00006579 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006580 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006581 Result = V;
6582 return true;
6583 }
Richard Smithfddd3842011-12-30 21:15:51 +00006584 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006585
Richard Smith2d406342011-10-22 21:10:00 +00006586 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006587 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006588 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006589 bool VisitInitListExpr(const InitListExpr *E);
6590 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006591 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006592 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006593 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006594 };
6595} // end anonymous namespace
6596
6597static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006598 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006599 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006600}
6601
George Burgess IV533ff002015-12-11 00:23:35 +00006602bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006603 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006604 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006605
Richard Smith161f09a2011-12-06 22:44:34 +00006606 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006607 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006608
Eli Friedmanc757de22011-03-25 00:43:55 +00006609 switch (E->getCastKind()) {
6610 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006611 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006612 if (SETy->isIntegerType()) {
6613 APSInt IntResult;
6614 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006615 return false;
6616 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006617 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006618 APFloat FloatResult(0.0);
6619 if (!EvaluateFloat(SE, FloatResult, Info))
6620 return false;
6621 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006622 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006623 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006624 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006625
6626 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006627 SmallVector<APValue, 4> Elts(NElts, Val);
6628 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006629 }
Eli Friedman803acb32011-12-22 03:51:45 +00006630 case CK_BitCast: {
6631 // Evaluate the operand into an APInt we can extract from.
6632 llvm::APInt SValInt;
6633 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6634 return false;
6635 // Extract the elements
6636 QualType EltTy = VTy->getElementType();
6637 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6638 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6639 SmallVector<APValue, 4> Elts;
6640 if (EltTy->isRealFloatingType()) {
6641 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006642 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006643 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006644 FloatEltSize = 80;
6645 for (unsigned i = 0; i < NElts; i++) {
6646 llvm::APInt Elt;
6647 if (BigEndian)
6648 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6649 else
6650 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006651 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006652 }
6653 } else if (EltTy->isIntegerType()) {
6654 for (unsigned i = 0; i < NElts; i++) {
6655 llvm::APInt Elt;
6656 if (BigEndian)
6657 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6658 else
6659 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6660 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6661 }
6662 } else {
6663 return Error(E);
6664 }
6665 return Success(Elts, E);
6666 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006667 default:
Richard Smith11562c52011-10-28 17:51:58 +00006668 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006669 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006670}
6671
Richard Smith2d406342011-10-22 21:10:00 +00006672bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006673VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006674 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006675 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006676 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006677
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006678 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006679 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006680
Eli Friedmanb9c71292012-01-03 23:24:20 +00006681 // The number of initializers can be less than the number of
6682 // vector elements. For OpenCL, this can be due to nested vector
Daniel Jasperffdee092017-05-02 19:21:42 +00006683 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00006684 // should be initialized with zeroes.
6685 unsigned CountInits = 0, CountElts = 0;
6686 while (CountElts < NumElements) {
6687 // Handle nested vector initialization.
Daniel Jasperffdee092017-05-02 19:21:42 +00006688 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006689 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006690 APValue v;
6691 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6692 return Error(E);
6693 unsigned vlen = v.getVectorLength();
Daniel Jasperffdee092017-05-02 19:21:42 +00006694 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00006695 Elements.push_back(v.getVectorElt(j));
6696 CountElts += vlen;
6697 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006698 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006699 if (CountInits < NumInits) {
6700 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006701 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006702 } else // trailing integer zero.
6703 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6704 Elements.push_back(APValue(sInt));
6705 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006706 } else {
6707 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006708 if (CountInits < NumInits) {
6709 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006710 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006711 } else // trailing float zero.
6712 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6713 Elements.push_back(APValue(f));
6714 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006715 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006716 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006717 }
Richard Smith2d406342011-10-22 21:10:00 +00006718 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006719}
6720
Richard Smith2d406342011-10-22 21:10:00 +00006721bool
Richard Smithfddd3842011-12-30 21:15:51 +00006722VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006723 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006724 QualType EltTy = VT->getElementType();
6725 APValue ZeroElement;
6726 if (EltTy->isIntegerType())
6727 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6728 else
6729 ZeroElement =
6730 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6731
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006732 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006733 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006734}
6735
Richard Smith2d406342011-10-22 21:10:00 +00006736bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006737 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006738 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006739}
6740
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006741//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006742// Array Evaluation
6743//===----------------------------------------------------------------------===//
6744
6745namespace {
6746 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006747 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006748 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006749 APValue &Result;
6750 public:
6751
Richard Smithd62306a2011-11-10 06:34:14 +00006752 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6753 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006754
6755 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006756 assert((V.isArray() || V.isLValue()) &&
6757 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006758 Result = V;
6759 return true;
6760 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006761
Richard Smithfddd3842011-12-30 21:15:51 +00006762 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006763 const ConstantArrayType *CAT =
6764 Info.Ctx.getAsConstantArrayType(E->getType());
6765 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006766 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006767
6768 Result = APValue(APValue::UninitArray(), 0,
6769 CAT->getSize().getZExtValue());
6770 if (!Result.hasArrayFiller()) return true;
6771
Richard Smithfddd3842011-12-30 21:15:51 +00006772 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006773 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006774 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006775 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006776 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006777 }
6778
Richard Smith52a980a2015-08-28 02:43:42 +00006779 bool VisitCallExpr(const CallExpr *E) {
6780 return handleCallExpr(E, Result, &This);
6781 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006782 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006783 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006784 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006785 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6786 const LValue &Subobject,
6787 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006788 };
6789} // end anonymous namespace
6790
Richard Smithd62306a2011-11-10 06:34:14 +00006791static bool EvaluateArray(const Expr *E, const LValue &This,
6792 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006793 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006794 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006795}
6796
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006797// Return true iff the given array filler may depend on the element index.
6798static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
6799 // For now, just whitelist non-class value-initialization and initialization
6800 // lists comprised of them.
6801 if (isa<ImplicitValueInitExpr>(FillerExpr))
6802 return false;
6803 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
6804 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
6805 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
6806 return true;
6807 }
6808 return false;
6809 }
6810 return true;
6811}
6812
Richard Smithf3e9e432011-11-07 09:22:26 +00006813bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6814 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6815 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006816 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006817
Richard Smithca2cfbf2011-12-22 01:07:19 +00006818 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6819 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006820 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006821 LValue LV;
6822 if (!EvaluateLValue(E->getInit(0), LV, Info))
6823 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006824 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006825 LV.moveInto(Val);
6826 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006827 }
6828
Richard Smith253c2a32012-01-27 01:14:48 +00006829 bool Success = true;
6830
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006831 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6832 "zero-initialized array shouldn't have any initialized elts");
6833 APValue Filler;
6834 if (Result.isArray() && Result.hasArrayFiller())
6835 Filler = Result.getArrayFiller();
6836
Richard Smith9543c5e2013-04-22 14:44:29 +00006837 unsigned NumEltsToInit = E->getNumInits();
6838 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006839 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006840
6841 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006842 // array element.
6843 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00006844 NumEltsToInit = NumElts;
6845
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006846 DEBUG(llvm::dbgs() << "The number of elements to initialize: " <<
6847 NumEltsToInit << ".\n");
6848
Richard Smith9543c5e2013-04-22 14:44:29 +00006849 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006850
6851 // If the array was previously zero-initialized, preserve the
6852 // zero-initialized values.
6853 if (!Filler.isUninit()) {
6854 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6855 Result.getArrayInitializedElt(I) = Filler;
6856 if (Result.hasArrayFiller())
6857 Result.getArrayFiller() = Filler;
6858 }
6859
Richard Smithd62306a2011-11-10 06:34:14 +00006860 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006861 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006862 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6863 const Expr *Init =
6864 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006865 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006866 Info, Subobject, Init) ||
6867 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006868 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006869 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006870 return false;
6871 Success = false;
6872 }
Richard Smithd62306a2011-11-10 06:34:14 +00006873 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006874
Richard Smith9543c5e2013-04-22 14:44:29 +00006875 if (!Result.hasArrayFiller())
6876 return Success;
6877
6878 // If we get here, we have a trivial filler, which we can just evaluate
6879 // once and splat over the rest of the array elements.
6880 assert(FillerExpr && "no array filler for incomplete init list");
6881 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6882 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006883}
6884
Richard Smith410306b2016-12-12 02:53:20 +00006885bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6886 if (E->getCommonExpr() &&
6887 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6888 Info, E->getCommonExpr()->getSourceExpr()))
6889 return false;
6890
6891 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6892
6893 uint64_t Elements = CAT->getSize().getZExtValue();
6894 Result = APValue(APValue::UninitArray(), Elements, Elements);
6895
6896 LValue Subobject = This;
6897 Subobject.addArray(Info, E, CAT);
6898
6899 bool Success = true;
6900 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6901 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6902 Info, Subobject, E->getSubExpr()) ||
6903 !HandleLValueArrayAdjustment(Info, E, Subobject,
6904 CAT->getElementType(), 1)) {
6905 if (!Info.noteFailure())
6906 return false;
6907 Success = false;
6908 }
6909 }
6910
6911 return Success;
6912}
6913
Richard Smith027bf112011-11-17 22:56:20 +00006914bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006915 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6916}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006917
Richard Smith9543c5e2013-04-22 14:44:29 +00006918bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6919 const LValue &Subobject,
6920 APValue *Value,
6921 QualType Type) {
6922 bool HadZeroInit = !Value->isUninit();
6923
6924 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6925 unsigned N = CAT->getSize().getZExtValue();
6926
6927 // Preserve the array filler if we had prior zero-initialization.
6928 APValue Filler =
6929 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6930 : APValue();
6931
6932 *Value = APValue(APValue::UninitArray(), N, N);
6933
6934 if (HadZeroInit)
6935 for (unsigned I = 0; I != N; ++I)
6936 Value->getArrayInitializedElt(I) = Filler;
6937
6938 // Initialize the elements.
6939 LValue ArrayElt = Subobject;
6940 ArrayElt.addArray(Info, E, CAT);
6941 for (unsigned I = 0; I != N; ++I)
6942 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6943 CAT->getElementType()) ||
6944 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6945 CAT->getElementType(), 1))
6946 return false;
6947
6948 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006949 }
Richard Smith027bf112011-11-17 22:56:20 +00006950
Richard Smith9543c5e2013-04-22 14:44:29 +00006951 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006952 return Error(E);
6953
Richard Smithb8348f52016-05-12 22:16:28 +00006954 return RecordExprEvaluator(Info, Subobject, *Value)
6955 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006956}
6957
Richard Smithf3e9e432011-11-07 09:22:26 +00006958//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006959// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006960//
6961// As a GNU extension, we support casting pointers to sufficiently-wide integer
6962// types and back in constant folding. Integer values are thus represented
6963// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006964//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006965
6966namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006967class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006968 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006969 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006970public:
Richard Smith2e312c82012-03-03 22:46:17 +00006971 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006972 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006973
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006974 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006975 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006976 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006977 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006978 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006979 assert(SI.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(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006982 return true;
6983 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006984 bool Success(const llvm::APSInt &SI, const Expr *E) {
6985 return Success(SI, E, Result);
6986 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006987
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006988 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00006989 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006990 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006991 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006992 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006993 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006994 Result.getInt().setIsUnsigned(
6995 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006996 return true;
6997 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006998 bool Success(const llvm::APInt &I, const Expr *E) {
6999 return Success(I, E, Result);
7000 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007001
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007002 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00007003 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007004 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007005 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007006 return true;
7007 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007008 bool Success(uint64_t Value, const Expr *E) {
7009 return Success(Value, E, Result);
7010 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007011
Ken Dyckdbc01912011-03-11 02:13:43 +00007012 bool Success(CharUnits Size, const Expr *E) {
7013 return Success(Size.getQuantity(), E);
7014 }
7015
Richard Smith2e312c82012-03-03 22:46:17 +00007016 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007017 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007018 Result = V;
7019 return true;
7020 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007021 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007022 }
Mike Stump11289f42009-09-09 15:08:12 +00007023
Richard Smithfddd3842011-12-30 21:15:51 +00007024 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007025
Peter Collingbournee9200682011-05-13 03:29:01 +00007026 //===--------------------------------------------------------------------===//
7027 // Visitor Methods
7028 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007029
Chris Lattner7174bf32008-07-12 00:38:25 +00007030 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007031 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007032 }
7033 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007034 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007035 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007036
7037 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7038 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007039 if (CheckReferencedDecl(E, E->getDecl()))
7040 return true;
7041
7042 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007043 }
7044 bool VisitMemberExpr(const MemberExpr *E) {
7045 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007046 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007047 return true;
7048 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007049
7050 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007051 }
7052
Peter Collingbournee9200682011-05-13 03:29:01 +00007053 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007054 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007055 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007056 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007057 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007058
Peter Collingbournee9200682011-05-13 03:29:01 +00007059 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007060 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007061
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007062 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007063 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007064 }
Mike Stump11289f42009-09-09 15:08:12 +00007065
Ted Kremeneke65b0862012-03-06 20:05:56 +00007066 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7067 return Success(E->getValue(), E);
7068 }
Richard Smith410306b2016-12-12 02:53:20 +00007069
7070 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7071 if (Info.ArrayInitIndex == uint64_t(-1)) {
7072 // We were asked to evaluate this subexpression independent of the
7073 // enclosing ArrayInitLoopExpr. We can't do that.
7074 Info.FFDiag(E);
7075 return false;
7076 }
7077 return Success(Info.ArrayInitIndex, E);
7078 }
Daniel Jasperffdee092017-05-02 19:21:42 +00007079
Richard Smith4ce706a2011-10-11 21:43:33 +00007080 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007081 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007082 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007083 }
7084
Douglas Gregor29c42f22012-02-24 07:38:34 +00007085 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7086 return Success(E->getValue(), E);
7087 }
7088
John Wiegley6242b6a2011-04-28 00:16:57 +00007089 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7090 return Success(E->getValue(), E);
7091 }
7092
John Wiegleyf9f65842011-04-25 06:54:41 +00007093 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7094 return Success(E->getValue(), E);
7095 }
7096
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007097 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007098 bool VisitUnaryImag(const UnaryOperator *E);
7099
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007100 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007101 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007102
Eli Friedman4e7a2412009-02-27 04:45:43 +00007103 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007104};
Chris Lattner05706e882008-07-11 18:11:29 +00007105} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007106
Richard Smith11562c52011-10-28 17:51:58 +00007107/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7108/// produce either the integer value or a pointer.
7109///
7110/// GCC has a heinous extension which folds casts between pointer types and
7111/// pointer-sized integral types. We support this by allowing the evaluation of
7112/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7113/// Some simple arithmetic on such values is supported (they are treated much
7114/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007115static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007116 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007117 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007118 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007119}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007120
Richard Smithf57d8cb2011-12-09 22:58:01 +00007121static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007122 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007123 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007124 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007125 if (!Val.isInt()) {
7126 // FIXME: It would be better to produce the diagnostic for casting
7127 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007128 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007129 return false;
7130 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007131 Result = Val.getInt();
7132 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007133}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007134
Richard Smithf57d8cb2011-12-09 22:58:01 +00007135/// Check whether the given declaration can be directly converted to an integral
7136/// rvalue. If not, no diagnostic is produced; there are other things we can
7137/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007138bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007139 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007140 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007141 // Check for signedness/width mismatches between E type and ECD value.
7142 bool SameSign = (ECD->getInitVal().isSigned()
7143 == E->getType()->isSignedIntegerOrEnumerationType());
7144 bool SameWidth = (ECD->getInitVal().getBitWidth()
7145 == Info.Ctx.getIntWidth(E->getType()));
7146 if (SameSign && SameWidth)
7147 return Success(ECD->getInitVal(), E);
7148 else {
7149 // Get rid of mismatch (otherwise Success assertions will fail)
7150 // by computing a new value matching the type of E.
7151 llvm::APSInt Val = ECD->getInitVal();
7152 if (!SameSign)
7153 Val.setIsSigned(!ECD->getInitVal().isSigned());
7154 if (!SameWidth)
7155 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7156 return Success(Val, E);
7157 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007158 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007159 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007160}
7161
Chris Lattner86ee2862008-10-06 06:40:35 +00007162/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7163/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007164static int EvaluateBuiltinClassifyType(const CallExpr *E,
7165 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007166 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007167 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007168 enum gcc_type_class {
7169 no_type_class = -1,
7170 void_type_class, integer_type_class, char_type_class,
7171 enumeral_type_class, boolean_type_class,
7172 pointer_type_class, reference_type_class, offset_type_class,
7173 real_type_class, complex_type_class,
7174 function_type_class, method_type_class,
7175 record_type_class, union_type_class,
7176 array_type_class, string_type_class,
7177 lang_type_class
7178 };
Mike Stump11289f42009-09-09 15:08:12 +00007179
7180 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007181 // ideal, however it is what gcc does.
7182 if (E->getNumArgs() == 0)
7183 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007184
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007185 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7186 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7187
7188 switch (CanTy->getTypeClass()) {
7189#define TYPE(ID, BASE)
7190#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7191#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7192#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7193#include "clang/AST/TypeNodes.def"
7194 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7195
7196 case Type::Builtin:
7197 switch (BT->getKind()) {
7198#define BUILTIN_TYPE(ID, SINGLETON_ID)
7199#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7200#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7201#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7202#include "clang/AST/BuiltinTypes.def"
7203 case BuiltinType::Void:
7204 return void_type_class;
7205
7206 case BuiltinType::Bool:
7207 return boolean_type_class;
7208
7209 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7210 case BuiltinType::UChar:
7211 case BuiltinType::UShort:
7212 case BuiltinType::UInt:
7213 case BuiltinType::ULong:
7214 case BuiltinType::ULongLong:
7215 case BuiltinType::UInt128:
7216 return integer_type_class;
7217
7218 case BuiltinType::NullPtr:
7219 return pointer_type_class;
7220
7221 case BuiltinType::WChar_U:
7222 case BuiltinType::Char16:
7223 case BuiltinType::Char32:
7224 case BuiltinType::ObjCId:
7225 case BuiltinType::ObjCClass:
7226 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007227#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7228 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007229#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007230 case BuiltinType::OCLSampler:
7231 case BuiltinType::OCLEvent:
7232 case BuiltinType::OCLClkEvent:
7233 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007234 case BuiltinType::OCLReserveID:
7235 case BuiltinType::Dependent:
7236 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7237 };
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007238 break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007239
7240 case Type::Enum:
7241 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7242 break;
7243
7244 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007245 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007246 break;
7247
7248 case Type::MemberPointer:
7249 if (CanTy->isMemberDataPointerType())
7250 return offset_type_class;
7251 else {
7252 // We expect member pointers to be either data or function pointers,
7253 // nothing else.
7254 assert(CanTy->isMemberFunctionPointerType());
7255 return method_type_class;
7256 }
7257
7258 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007259 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007260
7261 case Type::FunctionNoProto:
7262 case Type::FunctionProto:
7263 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7264
7265 case Type::Record:
7266 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7267 switch (RT->getDecl()->getTagKind()) {
7268 case TagTypeKind::TTK_Struct:
7269 case TagTypeKind::TTK_Class:
7270 case TagTypeKind::TTK_Interface:
7271 return record_type_class;
7272
7273 case TagTypeKind::TTK_Enum:
7274 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7275
7276 case TagTypeKind::TTK_Union:
7277 return union_type_class;
7278 }
7279 }
David Blaikie83d382b2011-09-23 05:06:16 +00007280 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007281
7282 case Type::ConstantArray:
7283 case Type::VariableArray:
7284 case Type::IncompleteArray:
7285 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7286
7287 case Type::BlockPointer:
7288 case Type::LValueReference:
7289 case Type::RValueReference:
7290 case Type::Vector:
7291 case Type::ExtVector:
7292 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007293 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007294 case Type::ObjCObject:
7295 case Type::ObjCInterface:
7296 case Type::ObjCObjectPointer:
7297 case Type::Pipe:
7298 case Type::Atomic:
7299 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7300 }
7301
7302 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007303}
7304
Richard Smith5fab0c92011-12-28 19:48:30 +00007305/// EvaluateBuiltinConstantPForLValue - Determine the result of
7306/// __builtin_constant_p when applied to the given lvalue.
7307///
7308/// An lvalue is only "constant" if it is a pointer or reference to the first
7309/// character of a string literal.
7310template<typename LValue>
7311static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007312 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007313 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7314}
7315
7316/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7317/// GCC as we can manage.
7318static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7319 QualType ArgType = Arg->getType();
7320
7321 // __builtin_constant_p always has one operand. The rules which gcc follows
7322 // are not precisely documented, but are as follows:
7323 //
7324 // - If the operand is of integral, floating, complex or enumeration type,
7325 // and can be folded to a known value of that type, it returns 1.
7326 // - If the operand and can be folded to a pointer to the first character
7327 // of a string literal (or such a pointer cast to an integral type), it
7328 // returns 1.
7329 //
7330 // Otherwise, it returns 0.
7331 //
7332 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7333 // its support for this does not currently work.
7334 if (ArgType->isIntegralOrEnumerationType()) {
7335 Expr::EvalResult Result;
7336 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7337 return false;
7338
7339 APValue &V = Result.Val;
7340 if (V.getKind() == APValue::Int)
7341 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007342 if (V.getKind() == APValue::LValue)
7343 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007344 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7345 return Arg->isEvaluatable(Ctx);
7346 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7347 LValue LV;
7348 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007349 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007350 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7351 : EvaluatePointer(Arg, LV, Info)) &&
7352 !Status.HasSideEffects)
7353 return EvaluateBuiltinConstantPForLValue(LV);
7354 }
7355
7356 // Anything else isn't considered to be sufficiently constant.
7357 return false;
7358}
7359
John McCall95007602010-05-10 23:27:23 +00007360/// Retrieves the "underlying object type" of the given expression,
7361/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007362static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007363 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7364 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007365 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007366 } else if (const Expr *E = B.get<const Expr*>()) {
7367 if (isa<CompoundLiteralExpr>(E))
7368 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007369 }
7370
7371 return QualType();
7372}
7373
George Burgess IV3a03fab2015-09-04 21:28:13 +00007374/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007375/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007376/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007377/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7378///
7379/// Always returns an RValue with a pointer representation.
7380static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7381 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7382
7383 auto *NoParens = E->IgnoreParens();
7384 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007385 if (Cast == nullptr)
7386 return NoParens;
7387
7388 // We only conservatively allow a few kinds of casts, because this code is
7389 // inherently a simple solution that seeks to support the common case.
7390 auto CastKind = Cast->getCastKind();
7391 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7392 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007393 return NoParens;
7394
7395 auto *SubExpr = Cast->getSubExpr();
7396 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7397 return NoParens;
7398 return ignorePointerCastsAndParens(SubExpr);
7399}
7400
George Burgess IVa51c4072015-10-16 01:49:01 +00007401/// Checks to see if the given LValue's Designator is at the end of the LValue's
7402/// record layout. e.g.
7403/// struct { struct { int a, b; } fst, snd; } obj;
7404/// obj.fst // no
7405/// obj.snd // yes
7406/// obj.fst.a // no
7407/// obj.fst.b // no
7408/// obj.snd.a // no
7409/// obj.snd.b // yes
7410///
7411/// Please note: this function is specialized for how __builtin_object_size
7412/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007413///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007414/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7415/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007416static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7417 assert(!LVal.Designator.Invalid);
7418
George Burgess IV4168d752016-06-27 19:40:41 +00007419 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7420 const RecordDecl *Parent = FD->getParent();
7421 Invalid = Parent->isInvalidDecl();
7422 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007423 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007424 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007425 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7426 };
7427
7428 auto &Base = LVal.getLValueBase();
7429 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7430 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007431 bool Invalid;
7432 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7433 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007434 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007435 for (auto *FD : IFD->chain()) {
7436 bool Invalid;
7437 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7438 return Invalid;
7439 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007440 }
7441 }
7442
George Burgess IVe3763372016-12-22 02:50:20 +00007443 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007444 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007445 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007446 // If we don't know the array bound, conservatively assume we're looking at
7447 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007448 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00007449 if (BaseType->isIncompleteArrayType())
7450 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7451 else
7452 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00007453 }
7454
7455 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7456 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007457 if (BaseType->isArrayType()) {
7458 // Because __builtin_object_size treats arrays as objects, we can ignore
7459 // the index iff this is the last array in the Designator.
7460 if (I + 1 == E)
7461 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007462 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7463 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007464 if (Index + 1 != CAT->getSize())
7465 return false;
7466 BaseType = CAT->getElementType();
7467 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007468 const auto *CT = BaseType->castAs<ComplexType>();
7469 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007470 if (Index != 1)
7471 return false;
7472 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007473 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007474 bool Invalid;
7475 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7476 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007477 BaseType = FD->getType();
7478 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007479 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007480 return false;
7481 }
7482 }
7483 return true;
7484}
7485
George Burgess IVe3763372016-12-22 02:50:20 +00007486/// Tests to see if the LValue has a user-specified designator (that isn't
7487/// necessarily valid). Note that this always returns 'true' if the LValue has
7488/// an unsized array as its first designator entry, because there's currently no
7489/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007490static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007491 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007492 return false;
7493
George Burgess IVe3763372016-12-22 02:50:20 +00007494 if (!LVal.Designator.Entries.empty())
7495 return LVal.Designator.isMostDerivedAnUnsizedArray();
7496
George Burgess IVa51c4072015-10-16 01:49:01 +00007497 if (!LVal.InvalidBase)
7498 return true;
7499
George Burgess IVe3763372016-12-22 02:50:20 +00007500 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7501 // the LValueBase.
7502 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7503 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007504}
7505
George Burgess IVe3763372016-12-22 02:50:20 +00007506/// Attempts to detect a user writing into a piece of memory that's impossible
7507/// to figure out the size of by just using types.
7508static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7509 const SubobjectDesignator &Designator = LVal.Designator;
7510 // Notes:
7511 // - Users can only write off of the end when we have an invalid base. Invalid
7512 // bases imply we don't know where the memory came from.
7513 // - We used to be a bit more aggressive here; we'd only be conservative if
7514 // the array at the end was flexible, or if it had 0 or 1 elements. This
7515 // broke some common standard library extensions (PR30346), but was
7516 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7517 // with some sort of whitelist. OTOH, it seems that GCC is always
7518 // conservative with the last element in structs (if it's an array), so our
7519 // current behavior is more compatible than a whitelisting approach would
7520 // be.
7521 return LVal.InvalidBase &&
7522 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7523 Designator.MostDerivedIsArrayElement &&
7524 isDesignatorAtObjectEnd(Ctx, LVal);
7525}
7526
7527/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7528/// Fails if the conversion would cause loss of precision.
7529static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7530 CharUnits &Result) {
7531 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7532 if (Int.ugt(CharUnitsMax))
7533 return false;
7534 Result = CharUnits::fromQuantity(Int.getZExtValue());
7535 return true;
7536}
7537
7538/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7539/// determine how many bytes exist from the beginning of the object to either
7540/// the end of the current subobject, or the end of the object itself, depending
7541/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007542///
George Burgess IVe3763372016-12-22 02:50:20 +00007543/// If this returns false, the value of Result is undefined.
7544static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7545 unsigned Type, const LValue &LVal,
7546 CharUnits &EndOffset) {
7547 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007548
George Burgess IV7fb7e362017-01-03 23:35:19 +00007549 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7550 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7551 return false;
7552 return HandleSizeof(Info, ExprLoc, Ty, Result);
7553 };
7554
George Burgess IVe3763372016-12-22 02:50:20 +00007555 // We want to evaluate the size of the entire object. This is a valid fallback
7556 // for when Type=1 and the designator is invalid, because we're asked for an
7557 // upper-bound.
7558 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7559 // Type=3 wants a lower bound, so we can't fall back to this.
7560 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007561 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007562
7563 llvm::APInt APEndOffset;
7564 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7565 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7566 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7567
7568 if (LVal.InvalidBase)
7569 return false;
7570
7571 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007572 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007573 }
7574
George Burgess IVe3763372016-12-22 02:50:20 +00007575 // We want to evaluate the size of a subobject.
7576 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007577
7578 // The following is a moderately common idiom in C:
7579 //
7580 // struct Foo { int a; char c[1]; };
7581 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7582 // strcpy(&F->c[0], Bar);
7583 //
George Burgess IVe3763372016-12-22 02:50:20 +00007584 // In order to not break too much legacy code, we need to support it.
7585 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7586 // If we can resolve this to an alloc_size call, we can hand that back,
7587 // because we know for certain how many bytes there are to write to.
7588 llvm::APInt APEndOffset;
7589 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7590 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7591 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7592
7593 // If we cannot determine the size of the initial allocation, then we can't
7594 // given an accurate upper-bound. However, we are still able to give
7595 // conservative lower-bounds for Type=3.
7596 if (Type == 1)
7597 return false;
7598 }
7599
7600 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007601 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007602 return false;
7603
George Burgess IVe3763372016-12-22 02:50:20 +00007604 // According to the GCC documentation, we want the size of the subobject
7605 // denoted by the pointer. But that's not quite right -- what we actually
7606 // want is the size of the immediately-enclosing array, if there is one.
7607 int64_t ElemsRemaining;
7608 if (Designator.MostDerivedIsArrayElement &&
7609 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7610 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7611 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7612 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7613 } else {
7614 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7615 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007616
George Burgess IVe3763372016-12-22 02:50:20 +00007617 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7618 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007619}
7620
George Burgess IVe3763372016-12-22 02:50:20 +00007621/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7622/// returns true and stores the result in @p Size.
7623///
7624/// If @p WasError is non-null, this will report whether the failure to evaluate
7625/// is to be treated as an Error in IntExprEvaluator.
7626static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7627 EvalInfo &Info, uint64_t &Size) {
7628 // Determine the denoted object.
7629 LValue LVal;
7630 {
7631 // The operand of __builtin_object_size is never evaluated for side-effects.
7632 // If there are any, but we can determine the pointed-to object anyway, then
7633 // ignore the side-effects.
7634 SpeculativeEvaluationRAII SpeculativeEval(Info);
7635 FoldOffsetRAII Fold(Info);
7636
7637 if (E->isGLValue()) {
7638 // It's possible for us to be given GLValues if we're called via
7639 // Expr::tryEvaluateObjectSize.
7640 APValue RVal;
7641 if (!EvaluateAsRValue(Info, E, RVal))
7642 return false;
7643 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007644 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7645 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007646 return false;
7647 }
7648
7649 // If we point to before the start of the object, there are no accessible
7650 // bytes.
7651 if (LVal.getLValueOffset().isNegative()) {
7652 Size = 0;
7653 return true;
7654 }
7655
7656 CharUnits EndOffset;
7657 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7658 return false;
7659
7660 // If we've fallen outside of the end offset, just pretend there's nothing to
7661 // write to/read from.
7662 if (EndOffset <= LVal.getLValueOffset())
7663 Size = 0;
7664 else
7665 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7666 return true;
John McCall95007602010-05-10 23:27:23 +00007667}
7668
Peter Collingbournee9200682011-05-13 03:29:01 +00007669bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007670 if (unsigned BuiltinOp = E->getBuiltinCallee())
7671 return VisitBuiltinCallExpr(E, BuiltinOp);
7672
7673 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7674}
7675
7676bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7677 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007678 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007679 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007680 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007681
7682 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007683 // The type was checked when we built the expression.
7684 unsigned Type =
7685 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7686 assert(Type <= 3 && "unexpected type");
7687
George Burgess IVe3763372016-12-22 02:50:20 +00007688 uint64_t Size;
7689 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7690 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007691
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007692 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007693 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007694
Richard Smith01ade172012-05-23 04:13:20 +00007695 // Expression had no side effects, but we couldn't statically determine the
7696 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007697 switch (Info.EvalMode) {
7698 case EvalInfo::EM_ConstantExpression:
7699 case EvalInfo::EM_PotentialConstantExpression:
7700 case EvalInfo::EM_ConstantFold:
7701 case EvalInfo::EM_EvaluateForOverflow:
7702 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007703 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007704 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007705 return Error(E);
7706 case EvalInfo::EM_ConstantExpressionUnevaluated:
7707 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007708 // Reduce it to a constant now.
7709 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007710 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007711
7712 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007713 }
7714
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007715 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007716 case Builtin::BI__builtin_bswap32:
7717 case Builtin::BI__builtin_bswap64: {
7718 APSInt Val;
7719 if (!EvaluateInteger(E->getArg(0), Val, Info))
7720 return false;
7721
7722 return Success(Val.byteSwap(), E);
7723 }
7724
Richard Smith8889a3d2013-06-13 06:26:32 +00007725 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007726 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007727
7728 // FIXME: BI__builtin_clrsb
7729 // FIXME: BI__builtin_clrsbl
7730 // FIXME: BI__builtin_clrsbll
7731
Richard Smith80b3c8e2013-06-13 05:04:16 +00007732 case Builtin::BI__builtin_clz:
7733 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007734 case Builtin::BI__builtin_clzll:
7735 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007736 APSInt Val;
7737 if (!EvaluateInteger(E->getArg(0), Val, Info))
7738 return false;
7739 if (!Val)
7740 return Error(E);
7741
7742 return Success(Val.countLeadingZeros(), E);
7743 }
7744
Richard Smith8889a3d2013-06-13 06:26:32 +00007745 case Builtin::BI__builtin_constant_p:
7746 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7747
Richard Smith80b3c8e2013-06-13 05:04:16 +00007748 case Builtin::BI__builtin_ctz:
7749 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007750 case Builtin::BI__builtin_ctzll:
7751 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007752 APSInt Val;
7753 if (!EvaluateInteger(E->getArg(0), Val, Info))
7754 return false;
7755 if (!Val)
7756 return Error(E);
7757
7758 return Success(Val.countTrailingZeros(), E);
7759 }
7760
Richard Smith8889a3d2013-06-13 06:26:32 +00007761 case Builtin::BI__builtin_eh_return_data_regno: {
7762 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7763 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7764 return Success(Operand, E);
7765 }
7766
7767 case Builtin::BI__builtin_expect:
7768 return Visit(E->getArg(0));
7769
7770 case Builtin::BI__builtin_ffs:
7771 case Builtin::BI__builtin_ffsl:
7772 case Builtin::BI__builtin_ffsll: {
7773 APSInt Val;
7774 if (!EvaluateInteger(E->getArg(0), Val, Info))
7775 return false;
7776
7777 unsigned N = Val.countTrailingZeros();
7778 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7779 }
7780
7781 case Builtin::BI__builtin_fpclassify: {
7782 APFloat Val(0.0);
7783 if (!EvaluateFloat(E->getArg(5), Val, Info))
7784 return false;
7785 unsigned Arg;
7786 switch (Val.getCategory()) {
7787 case APFloat::fcNaN: Arg = 0; break;
7788 case APFloat::fcInfinity: Arg = 1; break;
7789 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7790 case APFloat::fcZero: Arg = 4; break;
7791 }
7792 return Visit(E->getArg(Arg));
7793 }
7794
7795 case Builtin::BI__builtin_isinf_sign: {
7796 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007797 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007798 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7799 }
7800
Richard Smithea3019d2013-10-15 19:07:14 +00007801 case Builtin::BI__builtin_isinf: {
7802 APFloat Val(0.0);
7803 return EvaluateFloat(E->getArg(0), Val, Info) &&
7804 Success(Val.isInfinity() ? 1 : 0, E);
7805 }
7806
7807 case Builtin::BI__builtin_isfinite: {
7808 APFloat Val(0.0);
7809 return EvaluateFloat(E->getArg(0), Val, Info) &&
7810 Success(Val.isFinite() ? 1 : 0, E);
7811 }
7812
7813 case Builtin::BI__builtin_isnan: {
7814 APFloat Val(0.0);
7815 return EvaluateFloat(E->getArg(0), Val, Info) &&
7816 Success(Val.isNaN() ? 1 : 0, E);
7817 }
7818
7819 case Builtin::BI__builtin_isnormal: {
7820 APFloat Val(0.0);
7821 return EvaluateFloat(E->getArg(0), Val, Info) &&
7822 Success(Val.isNormal() ? 1 : 0, E);
7823 }
7824
Richard Smith8889a3d2013-06-13 06:26:32 +00007825 case Builtin::BI__builtin_parity:
7826 case Builtin::BI__builtin_parityl:
7827 case Builtin::BI__builtin_parityll: {
7828 APSInt Val;
7829 if (!EvaluateInteger(E->getArg(0), Val, Info))
7830 return false;
7831
7832 return Success(Val.countPopulation() % 2, E);
7833 }
7834
Richard Smith80b3c8e2013-06-13 05:04:16 +00007835 case Builtin::BI__builtin_popcount:
7836 case Builtin::BI__builtin_popcountl:
7837 case Builtin::BI__builtin_popcountll: {
7838 APSInt Val;
7839 if (!EvaluateInteger(E->getArg(0), Val, Info))
7840 return false;
7841
7842 return Success(Val.countPopulation(), E);
7843 }
7844
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007845 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007846 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007847 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007848 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007849 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007850 << /*isConstexpr*/0 << /*isConstructor*/0
7851 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007852 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007853 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007854 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007855 case Builtin::BI__builtin_strlen:
7856 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007857 // As an extension, we support __builtin_strlen() as a constant expression,
7858 // and support folding strlen() to a constant.
7859 LValue String;
7860 if (!EvaluatePointer(E->getArg(0), String, Info))
7861 return false;
7862
Richard Smith8110c9d2016-11-29 19:45:17 +00007863 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7864
Richard Smithe6c19f22013-11-15 02:10:04 +00007865 // Fast path: if it's a string literal, search the string value.
7866 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7867 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007868 // The string literal may have embedded null characters. Find the first
7869 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007870 StringRef Str = S->getBytes();
7871 int64_t Off = String.Offset.getQuantity();
7872 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007873 S->getCharByteWidth() == 1 &&
7874 // FIXME: Add fast-path for wchar_t too.
7875 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007876 Str = Str.substr(Off);
7877
7878 StringRef::size_type Pos = Str.find(0);
7879 if (Pos != StringRef::npos)
7880 Str = Str.substr(0, Pos);
7881
7882 return Success(Str.size(), E);
7883 }
7884
7885 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007886 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007887
7888 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007889 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7890 APValue Char;
7891 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7892 !Char.isInt())
7893 return false;
7894 if (!Char.getInt())
7895 return Success(Strlen, E);
7896 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7897 return false;
7898 }
7899 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007900
Richard Smithe151bab2016-11-11 23:43:35 +00007901 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007902 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007903 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007904 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007905 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007906 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007907 // A call to strlen is not a constant expression.
7908 if (Info.getLangOpts().CPlusPlus11)
7909 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7910 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007911 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007912 else
7913 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007914 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00007915 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007916 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007917 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007918 case Builtin::BI__builtin_wcsncmp:
7919 case Builtin::BI__builtin_memcmp:
7920 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007921 LValue String1, String2;
7922 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7923 !EvaluatePointer(E->getArg(1), String2, Info))
7924 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007925
7926 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7927
Richard Smithe151bab2016-11-11 23:43:35 +00007928 uint64_t MaxLength = uint64_t(-1);
7929 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007930 BuiltinOp != Builtin::BIwcscmp &&
7931 BuiltinOp != Builtin::BI__builtin_strcmp &&
7932 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007933 APSInt N;
7934 if (!EvaluateInteger(E->getArg(2), N, Info))
7935 return false;
7936 MaxLength = N.getExtValue();
7937 }
7938 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007939 BuiltinOp != Builtin::BIwmemcmp &&
7940 BuiltinOp != Builtin::BI__builtin_memcmp &&
7941 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007942 for (; MaxLength; --MaxLength) {
7943 APValue Char1, Char2;
7944 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7945 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7946 !Char1.isInt() || !Char2.isInt())
7947 return false;
7948 if (Char1.getInt() != Char2.getInt())
7949 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7950 if (StopAtNull && !Char1.getInt())
7951 return Success(0, E);
7952 assert(!(StopAtNull && !Char2.getInt()));
7953 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7954 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7955 return false;
7956 }
7957 // We hit the strncmp / memcmp limit.
7958 return Success(0, E);
7959 }
7960
Richard Smith01ba47d2012-04-13 00:45:38 +00007961 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007962 case Builtin::BI__atomic_is_lock_free:
7963 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007964 APSInt SizeVal;
7965 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7966 return false;
7967
7968 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7969 // of two less than the maximum inline atomic width, we know it is
7970 // lock-free. If the size isn't a power of two, or greater than the
7971 // maximum alignment where we promote atomics, we know it is not lock-free
7972 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7973 // the answer can only be determined at runtime; for example, 16-byte
7974 // atomics have lock-free implementations on some, but not all,
7975 // x86-64 processors.
7976
7977 // Check power-of-two.
7978 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007979 if (Size.isPowerOfTwo()) {
7980 // Check against inlining width.
7981 unsigned InlineWidthBits =
7982 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7983 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7984 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7985 Size == CharUnits::One() ||
7986 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7987 Expr::NPC_NeverValueDependent))
7988 // OK, we will inline appropriately-aligned operations of this size,
7989 // and _Atomic(T) is appropriately-aligned.
7990 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007991
Richard Smith01ba47d2012-04-13 00:45:38 +00007992 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7993 castAs<PointerType>()->getPointeeType();
7994 if (!PointeeType->isIncompleteType() &&
7995 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7996 // OK, we will inline operations on this object.
7997 return Success(1, E);
7998 }
7999 }
8000 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008001
Richard Smith01ba47d2012-04-13 00:45:38 +00008002 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8003 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008004 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00008005 case Builtin::BIomp_is_initial_device:
8006 // We can decide statically which value the runtime would return if called.
8007 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008008 }
Chris Lattner7174bf32008-07-12 00:38:25 +00008009}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008010
Richard Smith8b3497e2011-10-31 01:37:14 +00008011static bool HasSameBase(const LValue &A, const LValue &B) {
8012 if (!A.getLValueBase())
8013 return !B.getLValueBase();
8014 if (!B.getLValueBase())
8015 return false;
8016
Richard Smithce40ad62011-11-12 22:28:03 +00008017 if (A.getLValueBase().getOpaqueValue() !=
8018 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008019 const Decl *ADecl = GetLValueBaseDecl(A);
8020 if (!ADecl)
8021 return false;
8022 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00008023 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00008024 return false;
8025 }
8026
8027 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00008028 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00008029}
8030
Richard Smithd20f1e62014-10-21 23:01:04 +00008031/// \brief Determine whether this is a pointer past the end of the complete
8032/// object referred to by the lvalue.
8033static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8034 const LValue &LV) {
8035 // A null pointer can be viewed as being "past the end" but we don't
8036 // choose to look at it that way here.
8037 if (!LV.getLValueBase())
8038 return false;
8039
8040 // If the designator is valid and refers to a subobject, we're not pointing
8041 // past the end.
8042 if (!LV.getLValueDesignator().Invalid &&
8043 !LV.getLValueDesignator().isOnePastTheEnd())
8044 return false;
8045
David Majnemerc378ca52015-08-29 08:32:55 +00008046 // A pointer to an incomplete type might be past-the-end if the type's size is
8047 // zero. We cannot tell because the type is incomplete.
8048 QualType Ty = getType(LV.getLValueBase());
8049 if (Ty->isIncompleteType())
8050 return true;
8051
Richard Smithd20f1e62014-10-21 23:01:04 +00008052 // We're a past-the-end pointer if we point to the byte after the object,
8053 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008054 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008055 return LV.getLValueOffset() == Size;
8056}
8057
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008058namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008059
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008060/// \brief Data recursive integer evaluator of certain binary operators.
8061///
8062/// We use a data recursive algorithm for binary operators so that we are able
8063/// to handle extreme cases of chained binary operators without causing stack
8064/// overflow.
8065class DataRecursiveIntBinOpEvaluator {
8066 struct EvalResult {
8067 APValue Val;
8068 bool Failed;
8069
8070 EvalResult() : Failed(false) { }
8071
8072 void swap(EvalResult &RHS) {
8073 Val.swap(RHS.Val);
8074 Failed = RHS.Failed;
8075 RHS.Failed = false;
8076 }
8077 };
8078
8079 struct Job {
8080 const Expr *E;
8081 EvalResult LHSResult; // meaningful only for binary operator expression.
8082 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008083
David Blaikie73726062015-08-12 23:09:24 +00008084 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008085 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008086
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008087 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008088 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008089 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008090
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008091 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008092 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008093 };
8094
8095 SmallVector<Job, 16> Queue;
8096
8097 IntExprEvaluator &IntEval;
8098 EvalInfo &Info;
8099 APValue &FinalResult;
8100
8101public:
8102 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8103 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8104
8105 /// \brief True if \param E is a binary operator that we are going to handle
8106 /// data recursively.
8107 /// We handle binary operators that are comma, logical, or that have operands
8108 /// with integral or enumeration type.
8109 static bool shouldEnqueue(const BinaryOperator *E) {
8110 return E->getOpcode() == BO_Comma ||
8111 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00008112 (E->isRValue() &&
8113 E->getType()->isIntegralOrEnumerationType() &&
8114 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008115 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008116 }
8117
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008118 bool Traverse(const BinaryOperator *E) {
8119 enqueue(E);
8120 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008121 while (!Queue.empty())
8122 process(PrevResult);
8123
8124 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008125
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008126 FinalResult.swap(PrevResult.Val);
8127 return true;
8128 }
8129
8130private:
8131 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8132 return IntEval.Success(Value, E, Result);
8133 }
8134 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8135 return IntEval.Success(Value, E, Result);
8136 }
8137 bool Error(const Expr *E) {
8138 return IntEval.Error(E);
8139 }
8140 bool Error(const Expr *E, diag::kind D) {
8141 return IntEval.Error(E, D);
8142 }
8143
8144 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8145 return Info.CCEDiag(E, D);
8146 }
8147
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008148 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8149 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008150 bool &SuppressRHSDiags);
8151
8152 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8153 const BinaryOperator *E, APValue &Result);
8154
8155 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8156 Result.Failed = !Evaluate(Result.Val, Info, E);
8157 if (Result.Failed)
8158 Result.Val = APValue();
8159 }
8160
Richard Trieuba4d0872012-03-21 23:30:30 +00008161 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008162
8163 void enqueue(const Expr *E) {
8164 E = E->IgnoreParens();
8165 Queue.resize(Queue.size()+1);
8166 Queue.back().E = E;
8167 Queue.back().Kind = Job::AnyExprKind;
8168 }
8169};
8170
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008171}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008172
8173bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008174 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008175 bool &SuppressRHSDiags) {
8176 if (E->getOpcode() == BO_Comma) {
8177 // Ignore LHS but note if we could not evaluate it.
8178 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008179 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008180 return true;
8181 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008182
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008183 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008184 bool LHSAsBool;
8185 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008186 // We were able to evaluate the LHS, see if we can get away with not
8187 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008188 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8189 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008190 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008191 }
8192 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008193 LHSResult.Failed = true;
8194
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008195 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008196 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008197 if (!Info.noteSideEffect())
8198 return false;
8199
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008200 // We can't evaluate the LHS; however, sometimes the result
8201 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8202 // Don't ignore RHS and suppress diagnostics from this arm.
8203 SuppressRHSDiags = true;
8204 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008205
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008206 return true;
8207 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008208
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008209 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8210 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008211
George Burgess IVa145e252016-05-25 22:38:36 +00008212 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008213 return false; // Ignore RHS;
8214
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008215 return true;
8216}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008217
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008218static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8219 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008220 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8221 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8222 // offsets.
8223 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8224 CharUnits &Offset = LVal.getLValueOffset();
8225 uint64_t Offset64 = Offset.getQuantity();
8226 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8227 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8228 : Offset64 + Index64);
8229}
8230
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008231bool DataRecursiveIntBinOpEvaluator::
8232 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8233 const BinaryOperator *E, APValue &Result) {
8234 if (E->getOpcode() == BO_Comma) {
8235 if (RHSResult.Failed)
8236 return false;
8237 Result = RHSResult.Val;
8238 return true;
8239 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008240
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008241 if (E->isLogicalOp()) {
8242 bool lhsResult, rhsResult;
8243 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8244 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Daniel Jasperffdee092017-05-02 19:21:42 +00008245
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008246 if (LHSIsOK) {
8247 if (RHSIsOK) {
8248 if (E->getOpcode() == BO_LOr)
8249 return Success(lhsResult || rhsResult, E, Result);
8250 else
8251 return Success(lhsResult && rhsResult, E, Result);
8252 }
8253 } else {
8254 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008255 // We can't evaluate the LHS; however, sometimes the result
8256 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8257 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008258 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008259 }
8260 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008261
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008262 return false;
8263 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008264
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008265 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8266 E->getRHS()->getType()->isIntegralOrEnumerationType());
Daniel Jasperffdee092017-05-02 19:21:42 +00008267
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008268 if (LHSResult.Failed || RHSResult.Failed)
8269 return false;
Daniel Jasperffdee092017-05-02 19:21:42 +00008270
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008271 const APValue &LHSVal = LHSResult.Val;
8272 const APValue &RHSVal = RHSResult.Val;
Daniel Jasperffdee092017-05-02 19:21:42 +00008273
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008274 // Handle cases like (unsigned long)&a + 4.
8275 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8276 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008277 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008278 return true;
8279 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008280
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008281 // Handle cases like 4 + (unsigned long)&a
8282 if (E->getOpcode() == BO_Add &&
8283 RHSVal.isLValue() && LHSVal.isInt()) {
8284 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008285 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008286 return true;
8287 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008288
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008289 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8290 // Handle (intptr_t)&&A - (intptr_t)&&B.
8291 if (!LHSVal.getLValueOffset().isZero() ||
8292 !RHSVal.getLValueOffset().isZero())
8293 return false;
8294 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8295 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8296 if (!LHSExpr || !RHSExpr)
8297 return false;
8298 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8299 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8300 if (!LHSAddrExpr || !RHSAddrExpr)
8301 return false;
8302 // Make sure both labels come from the same function.
8303 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8304 RHSAddrExpr->getLabel()->getDeclContext())
8305 return false;
8306 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8307 return true;
8308 }
Richard Smith43e77732013-05-07 04:50:00 +00008309
8310 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008311 if (!LHSVal.isInt() || !RHSVal.isInt())
8312 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008313
8314 // Set up the width and signedness manually, in case it can't be deduced
8315 // from the operation we're performing.
8316 // FIXME: Don't do this in the cases where we can deduce it.
8317 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8318 E->getType()->isUnsignedIntegerOrEnumerationType());
8319 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8320 RHSVal.getInt(), Value))
8321 return false;
8322 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008323}
8324
Richard Trieuba4d0872012-03-21 23:30:30 +00008325void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008326 Job &job = Queue.back();
Daniel Jasperffdee092017-05-02 19:21:42 +00008327
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008328 switch (job.Kind) {
8329 case Job::AnyExprKind: {
8330 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8331 if (shouldEnqueue(Bop)) {
8332 job.Kind = Job::BinOpKind;
8333 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008334 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008335 }
8336 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008337
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008338 EvaluateExpr(job.E, Result);
8339 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008340 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008341 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008342
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008343 case Job::BinOpKind: {
8344 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008345 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008346 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008347 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008348 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008349 }
8350 if (SuppressRHSDiags)
8351 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008352 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008353 job.Kind = Job::BinOpVisitedLHSKind;
8354 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008355 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008356 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008357
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008358 case Job::BinOpVisitedLHSKind: {
8359 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8360 EvalResult RHS;
8361 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008362 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008363 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008364 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008365 }
8366 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008367
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008368 llvm_unreachable("Invalid Job::Kind!");
8369}
8370
George Burgess IV8c892b52016-05-25 22:31:54 +00008371namespace {
8372/// Used when we determine that we should fail, but can keep evaluating prior to
8373/// noting that we had a failure.
8374class DelayedNoteFailureRAII {
8375 EvalInfo &Info;
8376 bool NoteFailure;
8377
8378public:
8379 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8380 : Info(Info), NoteFailure(NoteFailure) {}
8381 ~DelayedNoteFailureRAII() {
8382 if (NoteFailure) {
8383 bool ContinueAfterFailure = Info.noteFailure();
8384 (void)ContinueAfterFailure;
8385 assert(ContinueAfterFailure &&
8386 "Shouldn't have kept evaluating on failure.");
8387 }
8388 }
8389};
8390}
8391
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008392bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008393 // We don't call noteFailure immediately because the assignment happens after
8394 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008395 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008396 return Error(E);
8397
George Burgess IV8c892b52016-05-25 22:31:54 +00008398 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008399 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8400 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008401
Anders Carlssonacc79812008-11-16 07:17:21 +00008402 QualType LHSTy = E->getLHS()->getType();
8403 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008404
Chandler Carruthb29a7432014-10-11 11:03:30 +00008405 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008406 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008407 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008408 if (E->isAssignmentOp()) {
8409 LValue LV;
8410 EvaluateLValue(E->getLHS(), LV, Info);
8411 LHSOK = false;
8412 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008413 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8414 if (LHSOK) {
8415 LHS.makeComplexFloat();
8416 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8417 }
8418 } else {
8419 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8420 }
George Burgess IVa145e252016-05-25 22:38:36 +00008421 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008422 return false;
8423
Chandler Carruthb29a7432014-10-11 11:03:30 +00008424 if (E->getRHS()->getType()->isRealFloatingType()) {
8425 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8426 return false;
8427 RHS.makeComplexFloat();
8428 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8429 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008430 return false;
8431
8432 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008433 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008434 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008435 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008436 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8437
John McCalle3027922010-08-25 11:45:40 +00008438 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008439 return Success((CR_r == APFloat::cmpEqual &&
8440 CR_i == APFloat::cmpEqual), E);
8441 else {
John McCalle3027922010-08-25 11:45:40 +00008442 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008443 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008444 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008445 CR_r == APFloat::cmpLessThan ||
8446 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008447 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008448 CR_i == APFloat::cmpLessThan ||
8449 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008450 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008451 } else {
John McCalle3027922010-08-25 11:45:40 +00008452 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008453 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8454 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8455 else {
John McCalle3027922010-08-25 11:45:40 +00008456 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008457 "Invalid compex comparison.");
8458 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8459 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8460 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008461 }
8462 }
Mike Stump11289f42009-09-09 15:08:12 +00008463
Anders Carlssonacc79812008-11-16 07:17:21 +00008464 if (LHSTy->isRealFloatingType() &&
8465 RHSTy->isRealFloatingType()) {
8466 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008467
Richard Smith253c2a32012-01-27 01:14:48 +00008468 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008469 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008470 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008471
Richard Smith253c2a32012-01-27 01:14:48 +00008472 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008473 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008474
Anders Carlssonacc79812008-11-16 07:17:21 +00008475 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008476
Anders Carlssonacc79812008-11-16 07:17:21 +00008477 switch (E->getOpcode()) {
8478 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008479 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008480 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008481 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008482 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008483 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008484 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008485 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008486 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008487 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008488 E);
John McCalle3027922010-08-25 11:45:40 +00008489 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008490 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008491 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008492 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008493 || CR == APFloat::cmpLessThan
8494 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008495 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008496 }
Mike Stump11289f42009-09-09 15:08:12 +00008497
Eli Friedmana38da572009-04-28 19:17:36 +00008498 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008499 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008500 LValue LHSValue, RHSValue;
8501
8502 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008503 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008504 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008505
Richard Smith253c2a32012-01-27 01:14:48 +00008506 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008507 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008508
Richard Smith8b3497e2011-10-31 01:37:14 +00008509 // Reject differing bases from the normal codepath; we special-case
8510 // comparisons to null.
8511 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008512 if (E->getOpcode() == BO_Sub) {
8513 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008514 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008515 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008516 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008517 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008518 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008519 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008520 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8521 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8522 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008523 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008524 // Make sure both labels come from the same function.
8525 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8526 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008527 return Error(E);
8528 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008529 }
Richard Smith83c68212011-10-31 05:11:32 +00008530 // Inequalities and subtractions between unrelated pointers have
8531 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008532 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008533 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008534 // A constant address may compare equal to the address of a symbol.
8535 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008536 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008537 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8538 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008539 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008540 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008541 // distinct addresses. In clang, the result of such a comparison is
8542 // unspecified, so it is not a constant expression. However, we do know
8543 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008544 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8545 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008546 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008547 // We can't tell whether weak symbols will end up pointing to the same
8548 // object.
8549 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008550 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008551 // We can't compare the address of the start of one object with the
8552 // past-the-end address of another object, per C++ DR1652.
8553 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8554 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8555 (RHSValue.Base && RHSValue.Offset.isZero() &&
8556 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8557 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008558 // We can't tell whether an object is at the same address as another
8559 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008560 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8561 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008562 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008563 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008564 // (Note that clang defaults to -fmerge-all-constants, which can
8565 // lead to inconsistent results for comparisons involving the address
8566 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008567 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008568 }
Eli Friedman64004332009-03-23 04:38:34 +00008569
Richard Smith1b470412012-02-01 08:10:20 +00008570 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8571 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8572
Richard Smith84f6dcf2012-02-02 01:16:57 +00008573 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8574 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8575
John McCalle3027922010-08-25 11:45:40 +00008576 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008577 // C++11 [expr.add]p6:
8578 // Unless both pointers point to elements of the same array object, or
8579 // one past the last element of the array object, the behavior is
8580 // undefined.
8581 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8582 !AreElementsOfSameArray(getType(LHSValue.Base),
8583 LHSDesignator, RHSDesignator))
8584 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8585
Chris Lattner882bdf22010-04-20 17:13:14 +00008586 QualType Type = E->getLHS()->getType();
8587 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008588
Richard Smithd62306a2011-11-10 06:34:14 +00008589 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008590 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008591 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008592
Richard Smith84c6b3d2013-09-10 21:34:14 +00008593 // As an extension, a type may have zero size (empty struct or union in
8594 // C, array of zero length). Pointer subtraction in such cases has
8595 // undefined behavior, so is not constant.
8596 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008597 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008598 << ElementType;
8599 return false;
8600 }
8601
Richard Smith1b470412012-02-01 08:10:20 +00008602 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8603 // and produce incorrect results when it overflows. Such behavior
8604 // appears to be non-conforming, but is common, so perhaps we should
8605 // assume the standard intended for such cases to be undefined behavior
8606 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008607
Richard Smith1b470412012-02-01 08:10:20 +00008608 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8609 // overflow in the final conversion to ptrdiff_t.
8610 APSInt LHS(
8611 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8612 APSInt RHS(
8613 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8614 APSInt ElemSize(
8615 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8616 APSInt TrueResult = (LHS - RHS) / ElemSize;
8617 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8618
Richard Smith0c6124b2015-12-03 01:36:22 +00008619 if (Result.extend(65) != TrueResult &&
8620 !HandleOverflow(Info, E, TrueResult, E->getType()))
8621 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008622 return Success(Result, E);
8623 }
Richard Smithde21b242012-01-31 06:41:30 +00008624
8625 // C++11 [expr.rel]p3:
8626 // Pointers to void (after pointer conversions) can be compared, with a
8627 // result defined as follows: If both pointers represent the same
8628 // address or are both the null pointer value, the result is true if the
8629 // operator is <= or >= and false otherwise; otherwise the result is
8630 // unspecified.
8631 // We interpret this as applying to pointers to *cv* void.
8632 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008633 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008634 CCEDiag(E, diag::note_constexpr_void_comparison);
8635
Richard Smith84f6dcf2012-02-02 01:16:57 +00008636 // C++11 [expr.rel]p2:
8637 // - If two pointers point to non-static data members of the same object,
8638 // or to subobjects or array elements fo such members, recursively, the
8639 // pointer to the later declared member compares greater provided the
8640 // two members have the same access control and provided their class is
8641 // not a union.
8642 // [...]
8643 // - Otherwise pointer comparisons are unspecified.
8644 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8645 E->isRelationalOp()) {
8646 bool WasArrayIndex;
8647 unsigned Mismatch =
8648 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8649 RHSDesignator, WasArrayIndex);
8650 // At the point where the designators diverge, the comparison has a
8651 // specified value if:
8652 // - we are comparing array indices
8653 // - we are comparing fields of a union, or fields with the same access
8654 // Otherwise, the result is unspecified and thus the comparison is not a
8655 // constant expression.
8656 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8657 Mismatch < RHSDesignator.Entries.size()) {
8658 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8659 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8660 if (!LF && !RF)
8661 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8662 else if (!LF)
8663 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8664 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8665 << RF->getParent() << RF;
8666 else if (!RF)
8667 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8668 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8669 << LF->getParent() << LF;
8670 else if (!LF->getParent()->isUnion() &&
8671 LF->getAccess() != RF->getAccess())
8672 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8673 << LF << LF->getAccess() << RF << RF->getAccess()
8674 << LF->getParent();
8675 }
8676 }
8677
Eli Friedman6c31cb42012-04-16 04:30:08 +00008678 // The comparison here must be unsigned, and performed with the same
8679 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008680 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8681 uint64_t CompareLHS = LHSOffset.getQuantity();
8682 uint64_t CompareRHS = RHSOffset.getQuantity();
8683 assert(PtrSize <= 64 && "Unexpected pointer width");
8684 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8685 CompareLHS &= Mask;
8686 CompareRHS &= Mask;
8687
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008688 // If there is a base and this is a relational operator, we can only
8689 // compare pointers within the object in question; otherwise, the result
8690 // depends on where the object is located in memory.
8691 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8692 QualType BaseTy = getType(LHSValue.Base);
8693 if (BaseTy->isIncompleteType())
8694 return Error(E);
8695 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8696 uint64_t OffsetLimit = Size.getQuantity();
8697 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8698 return Error(E);
8699 }
8700
Richard Smith8b3497e2011-10-31 01:37:14 +00008701 switch (E->getOpcode()) {
8702 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008703 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8704 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8705 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8706 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8707 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8708 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008709 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008710 }
8711 }
Richard Smith7bb00672012-02-01 01:42:44 +00008712
8713 if (LHSTy->isMemberPointerType()) {
8714 assert(E->isEqualityOp() && "unexpected member pointer operation");
8715 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8716
8717 MemberPtr LHSValue, RHSValue;
8718
8719 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008720 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008721 return false;
8722
8723 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8724 return false;
8725
8726 // C++11 [expr.eq]p2:
8727 // If both operands are null, they compare equal. Otherwise if only one is
8728 // null, they compare unequal.
8729 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8730 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8731 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8732 }
8733
8734 // Otherwise if either is a pointer to a virtual member function, the
8735 // result is unspecified.
8736 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8737 if (MD->isVirtual())
8738 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8739 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8740 if (MD->isVirtual())
8741 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8742
8743 // Otherwise they compare equal if and only if they would refer to the
8744 // same member of the same most derived object or the same subobject if
8745 // they were dereferenced with a hypothetical object of the associated
8746 // class type.
8747 bool Equal = LHSValue == RHSValue;
8748 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8749 }
8750
Richard Smithab44d9b2012-02-14 22:35:28 +00008751 if (LHSTy->isNullPtrType()) {
8752 assert(E->isComparisonOp() && "unexpected nullptr operation");
8753 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8754 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8755 // are compared, the result is true of the operator is <=, >= or ==, and
8756 // false otherwise.
8757 BinaryOperator::Opcode Opcode = E->getOpcode();
8758 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8759 }
8760
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008761 assert((!LHSTy->isIntegralOrEnumerationType() ||
8762 !RHSTy->isIntegralOrEnumerationType()) &&
8763 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8764 // We can't continue from here for non-integral types.
8765 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008766}
8767
Peter Collingbournee190dee2011-03-11 19:24:49 +00008768/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8769/// a result as the expression's type.
8770bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8771 const UnaryExprOrTypeTraitExpr *E) {
8772 switch(E->getKind()) {
8773 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008774 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008775 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008776 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008777 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008778 }
Eli Friedman64004332009-03-23 04:38:34 +00008779
Peter Collingbournee190dee2011-03-11 19:24:49 +00008780 case UETT_VecStep: {
8781 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008782
Peter Collingbournee190dee2011-03-11 19:24:49 +00008783 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008784 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008785
Peter Collingbournee190dee2011-03-11 19:24:49 +00008786 // The vec_step built-in functions that take a 3-component
8787 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8788 if (n == 3)
8789 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008790
Peter Collingbournee190dee2011-03-11 19:24:49 +00008791 return Success(n, E);
8792 } else
8793 return Success(1, E);
8794 }
8795
8796 case UETT_SizeOf: {
8797 QualType SrcTy = E->getTypeOfArgument();
8798 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8799 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008800 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8801 SrcTy = Ref->getPointeeType();
8802
Richard Smithd62306a2011-11-10 06:34:14 +00008803 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008804 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008805 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008806 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008807 }
Alexey Bataev00396512015-07-02 03:40:19 +00008808 case UETT_OpenMPRequiredSimdAlign:
8809 assert(E->isArgumentType());
8810 return Success(
8811 Info.Ctx.toCharUnitsFromBits(
8812 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8813 .getQuantity(),
8814 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008815 }
8816
8817 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008818}
8819
Peter Collingbournee9200682011-05-13 03:29:01 +00008820bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008821 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008822 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008823 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008824 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008825 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008826 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008827 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008828 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008829 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008830 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008831 APSInt IdxResult;
8832 if (!EvaluateInteger(Idx, IdxResult, Info))
8833 return false;
8834 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8835 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008836 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008837 CurrentType = AT->getElementType();
8838 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8839 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008840 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008841 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008842
James Y Knight7281c352015-12-29 22:31:18 +00008843 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008844 FieldDecl *MemberDecl = ON.getField();
8845 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008846 if (!RT)
8847 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008848 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008849 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008850 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008851 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008852 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008853 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008854 CurrentType = MemberDecl->getType().getNonReferenceType();
8855 break;
8856 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008857
James Y Knight7281c352015-12-29 22:31:18 +00008858 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008859 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008860
James Y Knight7281c352015-12-29 22:31:18 +00008861 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008862 CXXBaseSpecifier *BaseSpec = ON.getBase();
8863 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008864 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008865
8866 // Find the layout of the class whose base we are looking into.
8867 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008868 if (!RT)
8869 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008870 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008871 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008872 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8873
8874 // Find the base class itself.
8875 CurrentType = BaseSpec->getType();
8876 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8877 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008878 return Error(OOE);
Daniel Jasperffdee092017-05-02 19:21:42 +00008879
Douglas Gregord1702062010-04-29 00:18:15 +00008880 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008881 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008882 break;
8883 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008884 }
8885 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008886 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008887}
8888
Chris Lattnere13042c2008-07-11 19:10:17 +00008889bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008890 switch (E->getOpcode()) {
8891 default:
8892 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8893 // See C99 6.6p3.
8894 return Error(E);
8895 case UO_Extension:
8896 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8897 // If so, we could clear the diagnostic ID.
8898 return Visit(E->getSubExpr());
8899 case UO_Plus:
8900 // The result is just the value.
8901 return Visit(E->getSubExpr());
8902 case UO_Minus: {
8903 if (!Visit(E->getSubExpr()))
Aaron Ballmana5038552018-01-09 13:07:03 +00008904 return false;
8905 if (!Result.isInt()) return Error(E);
8906 const APSInt &Value = Result.getInt();
8907 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
8908 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8909 E->getType()))
8910 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008911 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008912 }
8913 case UO_Not: {
8914 if (!Visit(E->getSubExpr()))
8915 return false;
8916 if (!Result.isInt()) return Error(E);
8917 return Success(~Result.getInt(), E);
8918 }
8919 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008920 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008921 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008922 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008923 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008924 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008925 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008926}
Mike Stump11289f42009-09-09 15:08:12 +00008927
Chris Lattner477c4be2008-07-12 01:15:53 +00008928/// HandleCast - This is used to evaluate implicit or explicit casts where the
8929/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008930bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8931 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008932 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008933 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008934
Eli Friedmanc757de22011-03-25 00:43:55 +00008935 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008936 case CK_BaseToDerived:
8937 case CK_DerivedToBase:
8938 case CK_UncheckedDerivedToBase:
8939 case CK_Dynamic:
8940 case CK_ToUnion:
8941 case CK_ArrayToPointerDecay:
8942 case CK_FunctionToPointerDecay:
8943 case CK_NullToPointer:
8944 case CK_NullToMemberPointer:
8945 case CK_BaseToDerivedMemberPointer:
8946 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008947 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008948 case CK_ConstructorConversion:
8949 case CK_IntegralToPointer:
8950 case CK_ToVoid:
8951 case CK_VectorSplat:
8952 case CK_IntegralToFloating:
8953 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008954 case CK_CPointerToObjCPointerCast:
8955 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008956 case CK_AnyPointerToBlockPointerCast:
8957 case CK_ObjCObjectLValueCast:
8958 case CK_FloatingRealToComplex:
8959 case CK_FloatingComplexToReal:
8960 case CK_FloatingComplexCast:
8961 case CK_FloatingComplexToIntegralComplex:
8962 case CK_IntegralRealToComplex:
8963 case CK_IntegralComplexCast:
8964 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008965 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008966 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008967 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008968 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008969 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008970 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008971 llvm_unreachable("invalid cast kind for integral value");
8972
Eli Friedman9faf2f92011-03-25 19:07:11 +00008973 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008974 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008975 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008976 case CK_ARCProduceObject:
8977 case CK_ARCConsumeObject:
8978 case CK_ARCReclaimReturnedObject:
8979 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008980 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008981 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008982
Richard Smith4ef685b2012-01-17 21:17:26 +00008983 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008984 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008985 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008986 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008987 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008988
8989 case CK_MemberPointerToBoolean:
8990 case CK_PointerToBoolean:
8991 case CK_IntegralToBoolean:
8992 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008993 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008994 case CK_FloatingComplexToBoolean:
8995 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008996 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008997 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008998 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008999 uint64_t IntResult = BoolResult;
9000 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9001 IntResult = (uint64_t)-1;
9002 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009003 }
9004
Eli Friedmanc757de22011-03-25 00:43:55 +00009005 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00009006 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00009007 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00009008
Eli Friedman742421e2009-02-20 01:15:07 +00009009 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009010 // Allow casts of address-of-label differences if they are no-ops
9011 // or narrowing. (The narrowing case isn't actually guaranteed to
9012 // be constant-evaluatable except in some narrow cases which are hard
9013 // to detect here. We let it through on the assumption the user knows
9014 // what they are doing.)
9015 if (Result.isAddrLabelDiff())
9016 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00009017 // Only allow casts of lvalues if they are lossless.
9018 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9019 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009020
Richard Smith911e1422012-01-30 22:27:01 +00009021 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9022 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00009023 }
Mike Stump11289f42009-09-09 15:08:12 +00009024
Eli Friedmanc757de22011-03-25 00:43:55 +00009025 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00009026 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9027
John McCall45d55e42010-05-07 21:00:08 +00009028 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00009029 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009030 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009031
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009032 if (LV.getLValueBase()) {
9033 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009034 // FIXME: Allow a larger integer size than the pointer size, and allow
9035 // narrowing back down to pointer width in subsequent integral casts.
9036 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009037 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009038 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009039
Richard Smithcf74da72011-11-16 07:18:12 +00009040 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009041 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009042 return true;
9043 }
9044
Yaxun Liu402804b2016-12-15 08:09:08 +00009045 uint64_t V;
9046 if (LV.isNullPointer())
9047 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9048 else
9049 V = LV.getLValueOffset().getQuantity();
9050
9051 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00009052 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009053 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009054
Eli Friedmanc757de22011-03-25 00:43:55 +00009055 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009056 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009057 if (!EvaluateComplex(SubExpr, C, Info))
9058 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009059 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009060 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009061
Eli Friedmanc757de22011-03-25 00:43:55 +00009062 case CK_FloatingToIntegral: {
9063 APFloat F(0.0);
9064 if (!EvaluateFloat(SubExpr, F, Info))
9065 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009066
Richard Smith357362d2011-12-13 06:39:58 +00009067 APSInt Value;
9068 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9069 return false;
9070 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009071 }
9072 }
Mike Stump11289f42009-09-09 15:08:12 +00009073
Eli Friedmanc757de22011-03-25 00:43:55 +00009074 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009075}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009076
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009077bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9078 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009079 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009080 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9081 return false;
9082 if (!LV.isComplexInt())
9083 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009084 return Success(LV.getComplexIntReal(), E);
9085 }
9086
9087 return Visit(E->getSubExpr());
9088}
9089
Eli Friedman4e7a2412009-02-27 04:45:43 +00009090bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009091 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009092 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009093 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9094 return false;
9095 if (!LV.isComplexInt())
9096 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009097 return Success(LV.getComplexIntImag(), E);
9098 }
9099
Richard Smith4a678122011-10-24 18:44:57 +00009100 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009101 return Success(0, E);
9102}
9103
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009104bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9105 return Success(E->getPackLength(), E);
9106}
9107
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009108bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9109 return Success(E->getValue(), E);
9110}
9111
Chris Lattner05706e882008-07-11 18:11:29 +00009112//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009113// Float Evaluation
9114//===----------------------------------------------------------------------===//
9115
9116namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009117class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009118 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009119 APFloat &Result;
9120public:
9121 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009122 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009123
Richard Smith2e312c82012-03-03 22:46:17 +00009124 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009125 Result = V.getFloat();
9126 return true;
9127 }
Eli Friedman24c01542008-08-22 00:06:13 +00009128
Richard Smithfddd3842011-12-30 21:15:51 +00009129 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009130 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9131 return true;
9132 }
9133
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009134 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009135
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009136 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009137 bool VisitBinaryOperator(const BinaryOperator *E);
9138 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009139 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009140
John McCallb1fb0d32010-05-07 22:08:54 +00009141 bool VisitUnaryReal(const UnaryOperator *E);
9142 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009143
Richard Smithfddd3842011-12-30 21:15:51 +00009144 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009145};
9146} // end anonymous namespace
9147
9148static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009149 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009150 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009151}
9152
Jay Foad39c79802011-01-12 09:06:06 +00009153static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009154 QualType ResultTy,
9155 const Expr *Arg,
9156 bool SNaN,
9157 llvm::APFloat &Result) {
9158 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9159 if (!S) return false;
9160
9161 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9162
9163 llvm::APInt fill;
9164
9165 // Treat empty strings as if they were zero.
9166 if (S->getString().empty())
9167 fill = llvm::APInt(32, 0);
9168 else if (S->getString().getAsInteger(0, fill))
9169 return false;
9170
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009171 if (Context.getTargetInfo().isNan2008()) {
9172 if (SNaN)
9173 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9174 else
9175 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9176 } else {
9177 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9178 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9179 // a different encoding to what became a standard in 2008, and for pre-
9180 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9181 // sNaN. This is now known as "legacy NaN" encoding.
9182 if (SNaN)
9183 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9184 else
9185 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9186 }
9187
John McCall16291492010-02-28 13:00:19 +00009188 return true;
9189}
9190
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009191bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009192 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009193 default:
9194 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9195
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009196 case Builtin::BI__builtin_huge_val:
9197 case Builtin::BI__builtin_huge_valf:
9198 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009199 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009200 case Builtin::BI__builtin_inf:
9201 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009202 case Builtin::BI__builtin_infl:
9203 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009204 const llvm::fltSemantics &Sem =
9205 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009206 Result = llvm::APFloat::getInf(Sem);
9207 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009208 }
Mike Stump11289f42009-09-09 15:08:12 +00009209
John McCall16291492010-02-28 13:00:19 +00009210 case Builtin::BI__builtin_nans:
9211 case Builtin::BI__builtin_nansf:
9212 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009213 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009214 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9215 true, Result))
9216 return Error(E);
9217 return true;
John McCall16291492010-02-28 13:00:19 +00009218
Chris Lattner0b7282e2008-10-06 06:31:58 +00009219 case Builtin::BI__builtin_nan:
9220 case Builtin::BI__builtin_nanf:
9221 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009222 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +00009223 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009224 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009225 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9226 false, Result))
9227 return Error(E);
9228 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009229
9230 case Builtin::BI__builtin_fabs:
9231 case Builtin::BI__builtin_fabsf:
9232 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009233 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009234 if (!EvaluateFloat(E->getArg(0), Result, Info))
9235 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009236
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009237 if (Result.isNegative())
9238 Result.changeSign();
9239 return true;
9240
Richard Smith8889a3d2013-06-13 06:26:32 +00009241 // FIXME: Builtin::BI__builtin_powi
9242 // FIXME: Builtin::BI__builtin_powif
9243 // FIXME: Builtin::BI__builtin_powil
9244
Mike Stump11289f42009-09-09 15:08:12 +00009245 case Builtin::BI__builtin_copysign:
9246 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009247 case Builtin::BI__builtin_copysignl:
9248 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009249 APFloat RHS(0.);
9250 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9251 !EvaluateFloat(E->getArg(1), RHS, Info))
9252 return false;
9253 Result.copySign(RHS);
9254 return true;
9255 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009256 }
9257}
9258
John McCallb1fb0d32010-05-07 22:08:54 +00009259bool FloatExprEvaluator::VisitUnaryReal(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.FloatReal;
9265 return true;
9266 }
9267
9268 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009269}
9270
9271bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009272 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9273 ComplexValue CV;
9274 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9275 return false;
9276 Result = CV.FloatImag;
9277 return true;
9278 }
9279
Richard Smith4a678122011-10-24 18:44:57 +00009280 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009281 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9282 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009283 return true;
9284}
9285
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009286bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009287 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009288 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009289 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009290 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009291 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009292 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9293 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009294 Result.changeSign();
9295 return true;
9296 }
9297}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009298
Eli Friedman24c01542008-08-22 00:06:13 +00009299bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009300 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9301 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009302
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009303 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009304 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009305 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009306 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009307 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9308 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009309}
9310
9311bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9312 Result = E->getValue();
9313 return true;
9314}
9315
Peter Collingbournee9200682011-05-13 03:29:01 +00009316bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9317 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009318
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009319 switch (E->getCastKind()) {
9320 default:
Richard Smith11562c52011-10-28 17:51:58 +00009321 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009322
9323 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009324 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009325 return EvaluateInteger(SubExpr, IntResult, Info) &&
9326 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9327 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009328 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009329
9330 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009331 if (!Visit(SubExpr))
9332 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009333 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9334 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009335 }
John McCalld7646252010-11-14 08:17:51 +00009336
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009337 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009338 ComplexValue V;
9339 if (!EvaluateComplex(SubExpr, V, Info))
9340 return false;
9341 Result = V.getComplexFloatReal();
9342 return true;
9343 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009344 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009345}
9346
Eli Friedman24c01542008-08-22 00:06:13 +00009347//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009348// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009349//===----------------------------------------------------------------------===//
9350
9351namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009352class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009353 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009354 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009355
Anders Carlsson537969c2008-11-16 20:27:53 +00009356public:
John McCall93d91dc2010-05-07 17:22:02 +00009357 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009358 : ExprEvaluatorBaseTy(info), Result(Result) {}
9359
Richard Smith2e312c82012-03-03 22:46:17 +00009360 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009361 Result.setFrom(V);
9362 return true;
9363 }
Mike Stump11289f42009-09-09 15:08:12 +00009364
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009365 bool ZeroInitialization(const Expr *E);
9366
Anders Carlsson537969c2008-11-16 20:27:53 +00009367 //===--------------------------------------------------------------------===//
9368 // Visitor Methods
9369 //===--------------------------------------------------------------------===//
9370
Peter Collingbournee9200682011-05-13 03:29:01 +00009371 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009372 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009373 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009374 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009375 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009376};
9377} // end anonymous namespace
9378
John McCall93d91dc2010-05-07 17:22:02 +00009379static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9380 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009381 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009382 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009383}
9384
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009385bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009386 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009387 if (ElemTy->isRealFloatingType()) {
9388 Result.makeComplexFloat();
9389 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9390 Result.FloatReal = Zero;
9391 Result.FloatImag = Zero;
9392 } else {
9393 Result.makeComplexInt();
9394 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9395 Result.IntReal = Zero;
9396 Result.IntImag = Zero;
9397 }
9398 return true;
9399}
9400
Peter Collingbournee9200682011-05-13 03:29:01 +00009401bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9402 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009403
9404 if (SubExpr->getType()->isRealFloatingType()) {
9405 Result.makeComplexFloat();
9406 APFloat &Imag = Result.FloatImag;
9407 if (!EvaluateFloat(SubExpr, Imag, Info))
9408 return false;
9409
9410 Result.FloatReal = APFloat(Imag.getSemantics());
9411 return true;
9412 } else {
9413 assert(SubExpr->getType()->isIntegerType() &&
9414 "Unexpected imaginary literal.");
9415
9416 Result.makeComplexInt();
9417 APSInt &Imag = Result.IntImag;
9418 if (!EvaluateInteger(SubExpr, Imag, Info))
9419 return false;
9420
9421 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9422 return true;
9423 }
9424}
9425
Peter Collingbournee9200682011-05-13 03:29:01 +00009426bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009427
John McCallfcef3cf2010-12-14 17:51:41 +00009428 switch (E->getCastKind()) {
9429 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009430 case CK_BaseToDerived:
9431 case CK_DerivedToBase:
9432 case CK_UncheckedDerivedToBase:
9433 case CK_Dynamic:
9434 case CK_ToUnion:
9435 case CK_ArrayToPointerDecay:
9436 case CK_FunctionToPointerDecay:
9437 case CK_NullToPointer:
9438 case CK_NullToMemberPointer:
9439 case CK_BaseToDerivedMemberPointer:
9440 case CK_DerivedToBaseMemberPointer:
9441 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009442 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009443 case CK_ConstructorConversion:
9444 case CK_IntegralToPointer:
9445 case CK_PointerToIntegral:
9446 case CK_PointerToBoolean:
9447 case CK_ToVoid:
9448 case CK_VectorSplat:
9449 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009450 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009451 case CK_IntegralToBoolean:
9452 case CK_IntegralToFloating:
9453 case CK_FloatingToIntegral:
9454 case CK_FloatingToBoolean:
9455 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009456 case CK_CPointerToObjCPointerCast:
9457 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009458 case CK_AnyPointerToBlockPointerCast:
9459 case CK_ObjCObjectLValueCast:
9460 case CK_FloatingComplexToReal:
9461 case CK_FloatingComplexToBoolean:
9462 case CK_IntegralComplexToReal:
9463 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009464 case CK_ARCProduceObject:
9465 case CK_ARCConsumeObject:
9466 case CK_ARCReclaimReturnedObject:
9467 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009468 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009469 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009470 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009471 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009472 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009473 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009474 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009475 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009476
John McCallfcef3cf2010-12-14 17:51:41 +00009477 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009478 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009479 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009480 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009481
9482 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009483 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009484 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009485 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009486
9487 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009488 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009489 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009490 return false;
9491
John McCallfcef3cf2010-12-14 17:51:41 +00009492 Result.makeComplexFloat();
9493 Result.FloatImag = APFloat(Real.getSemantics());
9494 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009495 }
9496
John McCallfcef3cf2010-12-14 17:51:41 +00009497 case CK_FloatingComplexCast: {
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
Richard Smith357362d2011-12-13 06:39:58 +00009505 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9506 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009507 }
9508
9509 case CK_FloatingComplexToIntegralComplex: {
9510 if (!Visit(E->getSubExpr()))
9511 return false;
9512
9513 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9514 QualType From
9515 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9516 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009517 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9518 To, Result.IntReal) &&
9519 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9520 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009521 }
9522
9523 case CK_IntegralRealToComplex: {
9524 APSInt &Real = Result.IntReal;
9525 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9526 return false;
9527
9528 Result.makeComplexInt();
9529 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9530 return true;
9531 }
9532
9533 case CK_IntegralComplexCast: {
9534 if (!Visit(E->getSubExpr()))
9535 return false;
9536
9537 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9538 QualType From
9539 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9540
Richard Smith911e1422012-01-30 22:27:01 +00009541 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9542 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009543 return true;
9544 }
9545
9546 case CK_IntegralComplexToFloatingComplex: {
9547 if (!Visit(E->getSubExpr()))
9548 return false;
9549
Ted Kremenek28831752012-08-23 20:46:57 +00009550 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009551 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009552 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009553 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009554 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9555 To, Result.FloatReal) &&
9556 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9557 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009558 }
9559 }
9560
9561 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009562}
9563
John McCall93d91dc2010-05-07 17:22:02 +00009564bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009565 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009566 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9567
Chandler Carrutha216cad2014-10-11 00:57:18 +00009568 // Track whether the LHS or RHS is real at the type system level. When this is
9569 // the case we can simplify our evaluation strategy.
9570 bool LHSReal = false, RHSReal = false;
9571
9572 bool LHSOK;
9573 if (E->getLHS()->getType()->isRealFloatingType()) {
9574 LHSReal = true;
9575 APFloat &Real = Result.FloatReal;
9576 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9577 if (LHSOK) {
9578 Result.makeComplexFloat();
9579 Result.FloatImag = APFloat(Real.getSemantics());
9580 }
9581 } else {
9582 LHSOK = Visit(E->getLHS());
9583 }
George Burgess IVa145e252016-05-25 22:38:36 +00009584 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009585 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009586
John McCall93d91dc2010-05-07 17:22:02 +00009587 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009588 if (E->getRHS()->getType()->isRealFloatingType()) {
9589 RHSReal = true;
9590 APFloat &Real = RHS.FloatReal;
9591 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9592 return false;
9593 RHS.makeComplexFloat();
9594 RHS.FloatImag = APFloat(Real.getSemantics());
9595 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009596 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009597
Chandler Carrutha216cad2014-10-11 00:57:18 +00009598 assert(!(LHSReal && RHSReal) &&
9599 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009600 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009601 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009602 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009603 if (Result.isComplexFloat()) {
9604 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9605 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009606 if (LHSReal)
9607 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9608 else if (!RHSReal)
9609 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9610 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009611 } else {
9612 Result.getComplexIntReal() += RHS.getComplexIntReal();
9613 Result.getComplexIntImag() += RHS.getComplexIntImag();
9614 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009615 break;
John McCalle3027922010-08-25 11:45:40 +00009616 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009617 if (Result.isComplexFloat()) {
9618 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9619 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009620 if (LHSReal) {
9621 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9622 Result.getComplexFloatImag().changeSign();
9623 } else if (!RHSReal) {
9624 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9625 APFloat::rmNearestTiesToEven);
9626 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009627 } else {
9628 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9629 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9630 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009631 break;
John McCalle3027922010-08-25 11:45:40 +00009632 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009633 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009634 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009635 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009636 // following naming scheme:
9637 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009638 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009639 APFloat &A = LHS.getComplexFloatReal();
9640 APFloat &B = LHS.getComplexFloatImag();
9641 APFloat &C = RHS.getComplexFloatReal();
9642 APFloat &D = RHS.getComplexFloatImag();
9643 APFloat &ResR = Result.getComplexFloatReal();
9644 APFloat &ResI = Result.getComplexFloatImag();
9645 if (LHSReal) {
9646 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9647 ResR = A * C;
9648 ResI = A * D;
9649 } else if (RHSReal) {
9650 ResR = C * A;
9651 ResI = C * B;
9652 } else {
9653 // In the fully general case, we need to handle NaNs and infinities
9654 // robustly.
9655 APFloat AC = A * C;
9656 APFloat BD = B * D;
9657 APFloat AD = A * D;
9658 APFloat BC = B * C;
9659 ResR = AC - BD;
9660 ResI = AD + BC;
9661 if (ResR.isNaN() && ResI.isNaN()) {
9662 bool Recalc = false;
9663 if (A.isInfinity() || B.isInfinity()) {
9664 A = APFloat::copySign(
9665 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9666 B = APFloat::copySign(
9667 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9668 if (C.isNaN())
9669 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9670 if (D.isNaN())
9671 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9672 Recalc = true;
9673 }
9674 if (C.isInfinity() || D.isInfinity()) {
9675 C = APFloat::copySign(
9676 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9677 D = APFloat::copySign(
9678 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9679 if (A.isNaN())
9680 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9681 if (B.isNaN())
9682 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9683 Recalc = true;
9684 }
9685 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9686 AD.isInfinity() || BC.isInfinity())) {
9687 if (A.isNaN())
9688 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9689 if (B.isNaN())
9690 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9691 if (C.isNaN())
9692 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9693 if (D.isNaN())
9694 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9695 Recalc = true;
9696 }
9697 if (Recalc) {
9698 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9699 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9700 }
9701 }
9702 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009703 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009704 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009705 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009706 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9707 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009708 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009709 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9710 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9711 }
9712 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009713 case BO_Div:
9714 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009715 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009716 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009717 // following naming scheme:
9718 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009719 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009720 APFloat &A = LHS.getComplexFloatReal();
9721 APFloat &B = LHS.getComplexFloatImag();
9722 APFloat &C = RHS.getComplexFloatReal();
9723 APFloat &D = RHS.getComplexFloatImag();
9724 APFloat &ResR = Result.getComplexFloatReal();
9725 APFloat &ResI = Result.getComplexFloatImag();
9726 if (RHSReal) {
9727 ResR = A / C;
9728 ResI = B / C;
9729 } else {
9730 if (LHSReal) {
9731 // No real optimizations we can do here, stub out with zero.
9732 B = APFloat::getZero(A.getSemantics());
9733 }
9734 int DenomLogB = 0;
9735 APFloat MaxCD = maxnum(abs(C), abs(D));
9736 if (MaxCD.isFinite()) {
9737 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009738 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9739 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009740 }
9741 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009742 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9743 APFloat::rmNearestTiesToEven);
9744 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9745 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009746 if (ResR.isNaN() && ResI.isNaN()) {
9747 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9748 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9749 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9750 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9751 D.isFinite()) {
9752 A = APFloat::copySign(
9753 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9754 B = APFloat::copySign(
9755 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9756 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9757 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9758 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9759 C = APFloat::copySign(
9760 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9761 D = APFloat::copySign(
9762 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9763 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9764 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9765 }
9766 }
9767 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009768 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009769 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9770 return Error(E, diag::note_expr_divide_by_zero);
9771
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009772 ComplexValue LHS = Result;
9773 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9774 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9775 Result.getComplexIntReal() =
9776 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9777 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9778 Result.getComplexIntImag() =
9779 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9780 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9781 }
9782 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009783 }
9784
John McCall93d91dc2010-05-07 17:22:02 +00009785 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009786}
9787
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009788bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9789 // Get the operand value into 'Result'.
9790 if (!Visit(E->getSubExpr()))
9791 return false;
9792
9793 switch (E->getOpcode()) {
9794 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009795 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009796 case UO_Extension:
9797 return true;
9798 case UO_Plus:
9799 // The result is always just the subexpr.
9800 return true;
9801 case UO_Minus:
9802 if (Result.isComplexFloat()) {
9803 Result.getComplexFloatReal().changeSign();
9804 Result.getComplexFloatImag().changeSign();
9805 }
9806 else {
9807 Result.getComplexIntReal() = -Result.getComplexIntReal();
9808 Result.getComplexIntImag() = -Result.getComplexIntImag();
9809 }
9810 return true;
9811 case UO_Not:
9812 if (Result.isComplexFloat())
9813 Result.getComplexFloatImag().changeSign();
9814 else
9815 Result.getComplexIntImag() = -Result.getComplexIntImag();
9816 return true;
9817 }
9818}
9819
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009820bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9821 if (E->getNumInits() == 2) {
9822 if (E->getType()->isComplexType()) {
9823 Result.makeComplexFloat();
9824 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9825 return false;
9826 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9827 return false;
9828 } else {
9829 Result.makeComplexInt();
9830 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9831 return false;
9832 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9833 return false;
9834 }
9835 return true;
9836 }
9837 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9838}
9839
Anders Carlsson537969c2008-11-16 20:27:53 +00009840//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009841// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9842// implicit conversion.
9843//===----------------------------------------------------------------------===//
9844
9845namespace {
9846class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009847 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009848 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +00009849 APValue &Result;
9850public:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009851 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9852 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +00009853
9854 bool Success(const APValue &V, const Expr *E) {
9855 Result = V;
9856 return true;
9857 }
9858
9859 bool ZeroInitialization(const Expr *E) {
9860 ImplicitValueInitExpr VIE(
9861 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009862 // For atomic-qualified class (and array) types in C++, initialize the
9863 // _Atomic-wrapped subobject directly, in-place.
9864 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9865 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +00009866 }
9867
9868 bool VisitCastExpr(const CastExpr *E) {
9869 switch (E->getCastKind()) {
9870 default:
9871 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9872 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009873 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9874 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +00009875 }
9876 }
9877};
9878} // end anonymous namespace
9879
Richard Smith64cb9ca2017-02-22 22:09:50 +00009880static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9881 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +00009882 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009883 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +00009884}
9885
9886//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009887// Void expression evaluation, primarily for a cast to void on the LHS of a
9888// comma operator
9889//===----------------------------------------------------------------------===//
9890
9891namespace {
9892class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009893 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009894public:
9895 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9896
Richard Smith2e312c82012-03-03 22:46:17 +00009897 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009898
Richard Smith7cd577b2017-08-17 19:35:50 +00009899 bool ZeroInitialization(const Expr *E) { return true; }
9900
Richard Smith42d3af92011-12-07 00:43:50 +00009901 bool VisitCastExpr(const CastExpr *E) {
9902 switch (E->getCastKind()) {
9903 default:
9904 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9905 case CK_ToVoid:
9906 VisitIgnoredValue(E->getSubExpr());
9907 return true;
9908 }
9909 }
Hal Finkela8443c32014-07-17 14:49:58 +00009910
9911 bool VisitCallExpr(const CallExpr *E) {
9912 switch (E->getBuiltinCallee()) {
9913 default:
9914 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9915 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009916 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009917 // The argument is not evaluated!
9918 return true;
9919 }
9920 }
Richard Smith42d3af92011-12-07 00:43:50 +00009921};
9922} // end anonymous namespace
9923
9924static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9925 assert(E->isRValue() && E->getType()->isVoidType());
9926 return VoidExprEvaluator(Info).Visit(E);
9927}
9928
9929//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009930// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009931//===----------------------------------------------------------------------===//
9932
Richard Smith2e312c82012-03-03 22:46:17 +00009933static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009934 // In C, function designators are not lvalues, but we evaluate them as if they
9935 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009936 QualType T = E->getType();
9937 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009938 LValue LV;
9939 if (!EvaluateLValue(E, LV, Info))
9940 return false;
9941 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009942 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009943 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009944 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009945 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009946 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009947 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009948 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009949 LValue LV;
9950 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009951 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009952 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009953 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009954 llvm::APFloat F(0.0);
9955 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009956 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009957 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009958 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009959 ComplexValue C;
9960 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009961 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009962 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009963 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009964 MemberPtr P;
9965 if (!EvaluateMemberPointer(E, P, Info))
9966 return false;
9967 P.moveInto(Result);
9968 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009969 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009970 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009971 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009972 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9973 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009974 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009975 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009976 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009977 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009978 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009979 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9980 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009981 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009982 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009983 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009984 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009985 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009986 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009987 if (!EvaluateVoid(E, Info))
9988 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009989 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009990 QualType Unqual = T.getAtomicUnqualifiedType();
9991 if (Unqual->isArrayType() || Unqual->isRecordType()) {
9992 LValue LV;
9993 LV.set(E, Info.CurrentCall->Index);
9994 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9995 if (!EvaluateAtomic(E, &LV, Value, Info))
9996 return false;
9997 } else {
9998 if (!EvaluateAtomic(E, nullptr, Result, Info))
9999 return false;
10000 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010001 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000010002 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000010003 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010004 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000010005 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000010006 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010007 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010008
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000010009 return true;
10010}
10011
Richard Smithb228a862012-02-15 02:18:13 +000010012/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10013/// cases, the in-place evaluation is essential, since later initializers for
10014/// an object can indirectly refer to subobjects which were initialized earlier.
10015static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000010016 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000010017 assert(!E->isValueDependent());
10018
Richard Smith7525ff62013-05-09 07:14:00 +000010019 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000010020 return false;
10021
10022 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000010023 // Evaluate arrays and record types in-place, so that later initializers can
10024 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000010025 QualType T = E->getType();
10026 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000010027 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010028 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000010029 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010030 else if (T->isAtomicType()) {
10031 QualType Unqual = T.getAtomicUnqualifiedType();
10032 if (Unqual->isArrayType() || Unqual->isRecordType())
10033 return EvaluateAtomic(E, &This, Result, Info);
10034 }
Richard Smithed5165f2011-11-04 05:33:44 +000010035 }
10036
10037 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010038 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010039}
10040
Richard Smithf57d8cb2011-12-09 22:58:01 +000010041/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10042/// lvalue-to-rvalue cast if it is an lvalue.
10043static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000010044 if (E->getType().isNull())
10045 return false;
10046
Nick Lewyckyc190f962017-05-02 01:06:16 +000010047 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000010048 return false;
10049
Richard Smith2e312c82012-03-03 22:46:17 +000010050 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010051 return false;
10052
10053 if (E->isGLValue()) {
10054 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000010055 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000010056 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010057 return false;
10058 }
10059
Richard Smith2e312c82012-03-03 22:46:17 +000010060 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000010061 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010062}
Richard Smith11562c52011-10-28 17:51:58 +000010063
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010064static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000010065 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010066 // Fast-path evaluations of integer literals, since we sometimes see files
10067 // containing vast quantities of these.
10068 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10069 Result.Val = APValue(APSInt(L->getValue(),
10070 L->getType()->isUnsignedIntegerType()));
10071 IsConst = true;
10072 return true;
10073 }
James Dennett0492ef02014-03-14 17:44:10 +000010074
10075 // This case should be rare, but we need to check it before we check on
10076 // the type below.
10077 if (Exp->getType().isNull()) {
10078 IsConst = false;
10079 return true;
10080 }
Daniel Jasperffdee092017-05-02 19:21:42 +000010081
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010082 // FIXME: Evaluating values of large array and record types can cause
10083 // performance problems. Only do so in C++11 for now.
10084 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10085 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010086 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010087 IsConst = false;
10088 return true;
10089 }
10090 return false;
10091}
10092
10093
Richard Smith7b553f12011-10-29 00:50:52 +000010094/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010095/// any crazy technique (that has nothing to do with language standards) that
10096/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010097/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10098/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +000010099bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010100 bool IsConst;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010101 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010102 return IsConst;
Daniel Jasperffdee092017-05-02 19:21:42 +000010103
Richard Smith6d4c6582013-11-05 22:18:15 +000010104 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010105 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +000010106}
10107
Jay Foad39c79802011-01-12 09:06:06 +000010108bool Expr::EvaluateAsBooleanCondition(bool &Result,
10109 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010110 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010111 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010112 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010113}
10114
Richard Smithce8eca52015-12-08 03:21:47 +000010115static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10116 Expr::SideEffectsKind SEK) {
10117 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10118 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10119}
10120
Richard Smith5fab0c92011-12-28 19:48:30 +000010121bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10122 SideEffectsKind AllowSideEffects) const {
10123 if (!getType()->isIntegralOrEnumerationType())
10124 return false;
10125
Richard Smith11562c52011-10-28 17:51:58 +000010126 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010127 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +000010128 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010129 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010130
Richard Smith11562c52011-10-28 17:51:58 +000010131 Result = ExprResult.Val.getInt();
10132 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010133}
10134
Richard Trieube234c32016-04-21 21:04:55 +000010135bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10136 SideEffectsKind AllowSideEffects) const {
10137 if (!getType()->isRealFloatingType())
10138 return false;
10139
10140 EvalResult ExprResult;
10141 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10142 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10143 return false;
10144
10145 Result = ExprResult.Val.getFloat();
10146 return true;
10147}
10148
Jay Foad39c79802011-01-12 09:06:06 +000010149bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010150 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010151
John McCall45d55e42010-05-07 21:00:08 +000010152 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010153 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10154 !CheckLValueConstantExpression(Info, getExprLoc(),
10155 Ctx.getLValueReferenceType(getType()), LV))
10156 return false;
10157
Richard Smith2e312c82012-03-03 22:46:17 +000010158 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010159 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010160}
10161
Richard Smithd0b4dd62011-12-19 06:19:21 +000010162bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10163 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010164 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010165 // FIXME: Evaluating initializers for large array and record types can cause
10166 // performance problems. Only do so in C++11 for now.
10167 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010168 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010169 return false;
10170
Richard Smithd0b4dd62011-12-19 06:19:21 +000010171 Expr::EvalStatus EStatus;
10172 EStatus.Diag = &Notes;
10173
Richard Smith0c6124b2015-12-03 01:36:22 +000010174 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10175 ? EvalInfo::EM_ConstantExpression
10176 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010177 InitInfo.setEvaluatingDecl(VD, Value);
10178
10179 LValue LVal;
10180 LVal.set(VD);
10181
Richard Smithfddd3842011-12-30 21:15:51 +000010182 // C++11 [basic.start.init]p2:
10183 // Variables with static storage duration or thread storage duration shall be
10184 // zero-initialized before any other initialization takes place.
10185 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010186 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010187 !VD->getType()->isReferenceType()) {
10188 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010189 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010190 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010191 return false;
10192 }
10193
Richard Smith7525ff62013-05-09 07:14:00 +000010194 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10195 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010196 EStatus.HasSideEffects)
10197 return false;
10198
10199 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10200 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010201}
10202
Richard Smith7b553f12011-10-29 00:50:52 +000010203/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10204/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010205bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010206 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010207 return EvaluateAsRValue(Result, Ctx) &&
10208 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010209}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010210
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010211APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010212 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010213 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010214 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010215 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010216 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010217 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010218 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010219
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010220 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010221}
John McCall864e3962010-05-07 05:32:02 +000010222
Richard Smithe9ff7702013-11-05 22:23:30 +000010223void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010224 bool IsConst;
10225 EvalResult EvalResult;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010226 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010227 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010228 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10229 }
10230}
10231
Richard Smithe6c01442013-06-05 00:46:14 +000010232bool Expr::EvalResult::isGlobalLValue() const {
10233 assert(Val.isLValue());
10234 return IsGlobalLValue(Val.getLValueBase());
10235}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010236
10237
John McCall864e3962010-05-07 05:32:02 +000010238/// isIntegerConstantExpr - this recursive routine will test if an expression is
10239/// an integer constant expression.
10240
10241/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10242/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010243
10244// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010245// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10246// and a (possibly null) SourceLocation indicating the location of the problem.
10247//
John McCall864e3962010-05-07 05:32:02 +000010248// Note that to reduce code duplication, this helper does no evaluation
10249// itself; the caller checks whether the expression is evaluatable, and
10250// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010251// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010252
Dan Gohman28ade552010-07-26 21:25:24 +000010253namespace {
10254
Richard Smith9e575da2012-12-28 13:25:52 +000010255enum ICEKind {
10256 /// This expression is an ICE.
10257 IK_ICE,
10258 /// This expression is not an ICE, but if it isn't evaluated, it's
10259 /// a legal subexpression for an ICE. This return value is used to handle
10260 /// the comma operator in C99 mode, and non-constant subexpressions.
10261 IK_ICEIfUnevaluated,
10262 /// This expression is not an ICE, and is not a legal subexpression for one.
10263 IK_NotICE
10264};
10265
John McCall864e3962010-05-07 05:32:02 +000010266struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010267 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010268 SourceLocation Loc;
10269
Richard Smith9e575da2012-12-28 13:25:52 +000010270 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010271};
10272
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010273}
Dan Gohman28ade552010-07-26 21:25:24 +000010274
Richard Smith9e575da2012-12-28 13:25:52 +000010275static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10276
10277static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010278
Craig Toppera31a8822013-08-22 07:09:37 +000010279static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010280 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010281 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010282 !EVResult.Val.isInt())
10283 return ICEDiag(IK_NotICE, E->getLocStart());
10284
John McCall864e3962010-05-07 05:32:02 +000010285 return NoDiag();
10286}
10287
Craig Toppera31a8822013-08-22 07:09:37 +000010288static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010289 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010290 if (!E->getType()->isIntegralOrEnumerationType())
10291 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010292
10293 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010294#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010295#define STMT(Node, Base) case Expr::Node##Class:
10296#define EXPR(Node, Base)
10297#include "clang/AST/StmtNodes.inc"
10298 case Expr::PredefinedExprClass:
10299 case Expr::FloatingLiteralClass:
10300 case Expr::ImaginaryLiteralClass:
10301 case Expr::StringLiteralClass:
10302 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010303 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010304 case Expr::MemberExprClass:
10305 case Expr::CompoundAssignOperatorClass:
10306 case Expr::CompoundLiteralExprClass:
10307 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010308 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010309 case Expr::ArrayInitLoopExprClass:
10310 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010311 case Expr::NoInitExprClass:
10312 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010313 case Expr::ImplicitValueInitExprClass:
10314 case Expr::ParenListExprClass:
10315 case Expr::VAArgExprClass:
10316 case Expr::AddrLabelExprClass:
10317 case Expr::StmtExprClass:
10318 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010319 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010320 case Expr::CXXDynamicCastExprClass:
10321 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010322 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010323 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010324 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010325 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010326 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010327 case Expr::CXXThisExprClass:
10328 case Expr::CXXThrowExprClass:
10329 case Expr::CXXNewExprClass:
10330 case Expr::CXXDeleteExprClass:
10331 case Expr::CXXPseudoDestructorExprClass:
10332 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010333 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010334 case Expr::DependentScopeDeclRefExprClass:
10335 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010336 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010337 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010338 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010339 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010340 case Expr::CXXTemporaryObjectExprClass:
10341 case Expr::CXXUnresolvedConstructExprClass:
10342 case Expr::CXXDependentScopeMemberExprClass:
10343 case Expr::UnresolvedMemberExprClass:
10344 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010345 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010346 case Expr::ObjCArrayLiteralClass:
10347 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010348 case Expr::ObjCEncodeExprClass:
10349 case Expr::ObjCMessageExprClass:
10350 case Expr::ObjCSelectorExprClass:
10351 case Expr::ObjCProtocolExprClass:
10352 case Expr::ObjCIvarRefExprClass:
10353 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010354 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010355 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010356 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010357 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010358 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010359 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010360 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010361 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010362 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010363 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010364 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010365 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010366 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010367 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010368 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010369 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010370 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010371 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010372 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000010373 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010374 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010375 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010376
Richard Smithf137f932014-01-25 20:50:08 +000010377 case Expr::InitListExprClass: {
10378 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10379 // form "T x = { a };" is equivalent to "T x = a;".
10380 // Unless we're initializing a reference, T is a scalar as it is known to be
10381 // of integral or enumeration type.
10382 if (E->isRValue())
10383 if (cast<InitListExpr>(E)->getNumInits() == 1)
10384 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10385 return ICEDiag(IK_NotICE, E->getLocStart());
10386 }
10387
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010388 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010389 case Expr::GNUNullExprClass:
10390 // GCC considers the GNU __null value to be an integral constant expression.
10391 return NoDiag();
10392
John McCall7c454bb2011-07-15 05:09:51 +000010393 case Expr::SubstNonTypeTemplateParmExprClass:
10394 return
10395 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10396
John McCall864e3962010-05-07 05:32:02 +000010397 case Expr::ParenExprClass:
10398 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010399 case Expr::GenericSelectionExprClass:
10400 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010401 case Expr::IntegerLiteralClass:
10402 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010403 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010404 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010405 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010406 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010407 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010408 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010409 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010410 return NoDiag();
10411 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010412 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010413 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10414 // constant expressions, but they can never be ICEs because an ICE cannot
10415 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010416 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010417 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010418 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010419 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010420 }
Richard Smith6365c912012-02-24 22:12:32 +000010421 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010422 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10423 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010424 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010425 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010426 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010427 // Parameter variables are never constants. Without this check,
10428 // getAnyInitializer() can find a default argument, which leads
10429 // to chaos.
10430 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010431 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010432
10433 // C++ 7.1.5.1p2
10434 // A variable of non-volatile const-qualified integral or enumeration
10435 // type initialized by an ICE can be used in ICEs.
10436 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010437 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010438 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010439
Richard Smithd0b4dd62011-12-19 06:19:21 +000010440 const VarDecl *VD;
10441 // Look for a declaration of this variable that has an initializer, and
10442 // check whether it is an ICE.
10443 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10444 return NoDiag();
10445 else
Richard Smith9e575da2012-12-28 13:25:52 +000010446 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010447 }
10448 }
Richard Smith9e575da2012-12-28 13:25:52 +000010449 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010450 }
John McCall864e3962010-05-07 05:32:02 +000010451 case Expr::UnaryOperatorClass: {
10452 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10453 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010454 case UO_PostInc:
10455 case UO_PostDec:
10456 case UO_PreInc:
10457 case UO_PreDec:
10458 case UO_AddrOf:
10459 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010460 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010461 // C99 6.6/3 allows increment and decrement within unevaluated
10462 // subexpressions of constant expressions, but they can never be ICEs
10463 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010464 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010465 case UO_Extension:
10466 case UO_LNot:
10467 case UO_Plus:
10468 case UO_Minus:
10469 case UO_Not:
10470 case UO_Real:
10471 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010472 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010473 }
Richard Smith9e575da2012-12-28 13:25:52 +000010474
John McCall864e3962010-05-07 05:32:02 +000010475 // OffsetOf falls through here.
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010476 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010477 }
10478 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010479 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10480 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10481 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10482 // compliance: we should warn earlier for offsetof expressions with
10483 // array subscripts that aren't ICEs, and if the array subscripts
10484 // are ICEs, the value of the offsetof must be an integer constant.
10485 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010486 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010487 case Expr::UnaryExprOrTypeTraitExprClass: {
10488 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10489 if ((Exp->getKind() == UETT_SizeOf) &&
10490 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010491 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010492 return NoDiag();
10493 }
10494 case Expr::BinaryOperatorClass: {
10495 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10496 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010497 case BO_PtrMemD:
10498 case BO_PtrMemI:
10499 case BO_Assign:
10500 case BO_MulAssign:
10501 case BO_DivAssign:
10502 case BO_RemAssign:
10503 case BO_AddAssign:
10504 case BO_SubAssign:
10505 case BO_ShlAssign:
10506 case BO_ShrAssign:
10507 case BO_AndAssign:
10508 case BO_XorAssign:
10509 case BO_OrAssign:
Richard Smithc70f1d62017-12-14 15:16:18 +000010510 case BO_Cmp: // FIXME: Re-enable once we can evaluate this.
Richard Smith62f65952011-10-24 22:35:48 +000010511 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10512 // constant expressions, but they can never be ICEs because an ICE cannot
10513 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010514 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010515
John McCalle3027922010-08-25 11:45:40 +000010516 case BO_Mul:
10517 case BO_Div:
10518 case BO_Rem:
10519 case BO_Add:
10520 case BO_Sub:
10521 case BO_Shl:
10522 case BO_Shr:
10523 case BO_LT:
10524 case BO_GT:
10525 case BO_LE:
10526 case BO_GE:
10527 case BO_EQ:
10528 case BO_NE:
10529 case BO_And:
10530 case BO_Xor:
10531 case BO_Or:
10532 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010533 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10534 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010535 if (Exp->getOpcode() == BO_Div ||
10536 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010537 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010538 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010539 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010540 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010541 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010542 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010543 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010544 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010545 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010546 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010547 }
10548 }
10549 }
John McCalle3027922010-08-25 11:45:40 +000010550 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010551 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010552 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10553 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010554 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10555 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010556 } else {
10557 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010558 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010559 }
10560 }
Richard Smith9e575da2012-12-28 13:25:52 +000010561 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010562 }
John McCalle3027922010-08-25 11:45:40 +000010563 case BO_LAnd:
10564 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010565 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10566 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010567 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010568 // Rare case where the RHS has a comma "side-effect"; we need
10569 // to actually check the condition to see whether the side
10570 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010571 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010572 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010573 return RHSResult;
10574 return NoDiag();
10575 }
10576
Richard Smith9e575da2012-12-28 13:25:52 +000010577 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010578 }
10579 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010580 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010581 }
10582 case Expr::ImplicitCastExprClass:
10583 case Expr::CStyleCastExprClass:
10584 case Expr::CXXFunctionalCastExprClass:
10585 case Expr::CXXStaticCastExprClass:
10586 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010587 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010588 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010589 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010590 if (isa<ExplicitCastExpr>(E)) {
10591 if (const FloatingLiteral *FL
10592 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10593 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10594 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10595 APSInt IgnoredVal(DestWidth, !DestSigned);
10596 bool Ignored;
10597 // If the value does not fit in the destination type, the behavior is
10598 // undefined, so we are not required to treat it as a constant
10599 // expression.
10600 if (FL->getValue().convertToInteger(IgnoredVal,
10601 llvm::APFloat::rmTowardZero,
10602 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010603 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010604 return NoDiag();
10605 }
10606 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010607 switch (cast<CastExpr>(E)->getCastKind()) {
10608 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010609 case CK_AtomicToNonAtomic:
10610 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010611 case CK_NoOp:
10612 case CK_IntegralToBoolean:
10613 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010614 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010615 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010616 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010617 }
John McCall864e3962010-05-07 05:32:02 +000010618 }
John McCallc07a0c72011-02-17 10:25:35 +000010619 case Expr::BinaryConditionalOperatorClass: {
10620 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10621 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010622 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010623 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010624 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10625 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10626 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010627 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010628 return FalseResult;
10629 }
John McCall864e3962010-05-07 05:32:02 +000010630 case Expr::ConditionalOperatorClass: {
10631 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10632 // If the condition (ignoring parens) is a __builtin_constant_p call,
10633 // then only the true side is actually considered in an integer constant
10634 // expression, and it is fully evaluated. This is an important GNU
10635 // extension. See GCC PR38377 for discussion.
10636 if (const CallExpr *CallCE
10637 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010638 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010639 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010640 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010641 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010642 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010643
Richard Smithf57d8cb2011-12-09 22:58:01 +000010644 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10645 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010646
Richard Smith9e575da2012-12-28 13:25:52 +000010647 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010648 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010649 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010650 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010651 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010652 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010653 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010654 return NoDiag();
10655 // Rare case where the diagnostics depend on which side is evaluated
10656 // Note that if we get here, CondResult is 0, and at least one of
10657 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010658 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010659 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010660 return TrueResult;
10661 }
10662 case Expr::CXXDefaultArgExprClass:
10663 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010664 case Expr::CXXDefaultInitExprClass:
10665 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010666 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010667 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010668 }
10669 }
10670
David Blaikiee4d798f2012-01-20 21:50:17 +000010671 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010672}
10673
Richard Smithf57d8cb2011-12-09 22:58:01 +000010674/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010675static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010676 const Expr *E,
10677 llvm::APSInt *Value,
10678 SourceLocation *Loc) {
10679 if (!E->getType()->isIntegralOrEnumerationType()) {
10680 if (Loc) *Loc = E->getExprLoc();
10681 return false;
10682 }
10683
Richard Smith66e05fe2012-01-18 05:21:49 +000010684 APValue Result;
10685 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010686 return false;
10687
Richard Smith98710fc2014-11-13 23:03:19 +000010688 if (!Result.isInt()) {
10689 if (Loc) *Loc = E->getExprLoc();
10690 return false;
10691 }
10692
Richard Smith66e05fe2012-01-18 05:21:49 +000010693 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010694 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010695}
10696
Craig Toppera31a8822013-08-22 07:09:37 +000010697bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10698 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010699 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010700 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010701
Richard Smith9e575da2012-12-28 13:25:52 +000010702 ICEDiag D = CheckICE(this, Ctx);
10703 if (D.Kind != IK_ICE) {
10704 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010705 return false;
10706 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010707 return true;
10708}
10709
Craig Toppera31a8822013-08-22 07:09:37 +000010710bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010711 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010712 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010713 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10714
10715 if (!isIntegerConstantExpr(Ctx, Loc))
10716 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010717 // The only possible side-effects here are due to UB discovered in the
10718 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10719 // required to treat the expression as an ICE, so we produce the folded
10720 // value.
10721 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010722 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010723 return true;
10724}
Richard Smith66e05fe2012-01-18 05:21:49 +000010725
Craig Toppera31a8822013-08-22 07:09:37 +000010726bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010727 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010728}
10729
Craig Toppera31a8822013-08-22 07:09:37 +000010730bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010731 SourceLocation *Loc) const {
10732 // We support this checking in C++98 mode in order to diagnose compatibility
10733 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010734 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010735
Richard Smith98a0a492012-02-14 21:38:30 +000010736 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010737 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010738 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010739 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010740 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010741
10742 APValue Scratch;
10743 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10744
10745 if (!Diags.empty()) {
10746 IsConstExpr = false;
10747 if (Loc) *Loc = Diags[0].first;
10748 } else if (!IsConstExpr) {
10749 // FIXME: This shouldn't happen.
10750 if (Loc) *Loc = getExprLoc();
10751 }
10752
10753 return IsConstExpr;
10754}
Richard Smith253c2a32012-01-27 01:14:48 +000010755
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010756bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10757 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010758 ArrayRef<const Expr*> Args,
10759 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010760 Expr::EvalStatus Status;
10761 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10762
George Burgess IV177399e2017-01-09 04:12:14 +000010763 LValue ThisVal;
10764 const LValue *ThisPtr = nullptr;
10765 if (This) {
10766#ifndef NDEBUG
10767 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10768 assert(MD && "Don't provide `this` for non-methods.");
10769 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10770#endif
10771 if (EvaluateObjectArgument(Info, This, ThisVal))
10772 ThisPtr = &ThisVal;
10773 if (Info.EvalStatus.HasSideEffects)
10774 return false;
10775 }
10776
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010777 ArgVector ArgValues(Args.size());
10778 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10779 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010780 if ((*I)->isValueDependent() ||
10781 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010782 // If evaluation fails, throw away the argument entirely.
10783 ArgValues[I - Args.begin()] = APValue();
10784 if (Info.EvalStatus.HasSideEffects)
10785 return false;
10786 }
10787
10788 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010789 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010790 ArgValues.data());
10791 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10792}
10793
Richard Smith253c2a32012-01-27 01:14:48 +000010794bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010795 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010796 PartialDiagnosticAt> &Diags) {
10797 // FIXME: It would be useful to check constexpr function templates, but at the
10798 // moment the constant expression evaluator cannot cope with the non-rigorous
10799 // ASTs which we build for dependent expressions.
10800 if (FD->isDependentContext())
10801 return true;
10802
10803 Expr::EvalStatus Status;
10804 Status.Diag = &Diags;
10805
Richard Smith6d4c6582013-11-05 22:18:15 +000010806 EvalInfo Info(FD->getASTContext(), Status,
10807 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010808
10809 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010810 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010811
Richard Smith7525ff62013-05-09 07:14:00 +000010812 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010813 // is a temporary being used as the 'this' pointer.
10814 LValue This;
10815 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010816 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010817
Richard Smith253c2a32012-01-27 01:14:48 +000010818 ArrayRef<const Expr*> Args;
10819
Richard Smith2e312c82012-03-03 22:46:17 +000010820 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010821 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10822 // Evaluate the call as a constant initializer, to allow the construction
10823 // of objects of non-literal types.
10824 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010825 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10826 } else {
10827 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010828 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010829 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010830 }
Richard Smith253c2a32012-01-27 01:14:48 +000010831
10832 return Diags.empty();
10833}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010834
10835bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10836 const FunctionDecl *FD,
10837 SmallVectorImpl<
10838 PartialDiagnosticAt> &Diags) {
10839 Expr::EvalStatus Status;
10840 Status.Diag = &Diags;
10841
10842 EvalInfo Info(FD->getASTContext(), Status,
10843 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10844
10845 // Fabricate a call stack frame to give the arguments a plausible cover story.
10846 ArrayRef<const Expr*> Args;
10847 ArgVector ArgValues(0);
10848 bool Success = EvaluateArgs(Args, ArgValues, Info);
10849 (void)Success;
10850 assert(Success &&
10851 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010852 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010853
10854 APValue ResultScratch;
10855 Evaluate(ResultScratch, Info, E);
10856 return Diags.empty();
10857}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010858
10859bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10860 unsigned Type) const {
10861 if (!getType()->isPointerType())
10862 return false;
10863
10864 Expr::EvalStatus Status;
10865 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010866 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010867}