blob: 28f044611724647a57b63bd4ae9f60f92b547b15 [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
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
Richard Smith84401042013-06-03 05:03:02 +000066
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000079 // for it directly. Otherwise use the type after adjustment.
80 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000081 return Inner->getType();
82 }
83
84 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000085 }
86
Richard Smithd62306a2011-11-10 06:34:14 +000087 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000088 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000089 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000090 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000091 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000093 return Value;
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000098 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000099 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000110 }
111
George Burgess IVe3763372016-12-22 02:50:20 +0000112 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
113 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
114 const FunctionDecl *Callee = CE->getDirectCallee();
115 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
116 }
117
118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119 /// This will look through a single cast.
120 ///
121 /// Returns null if we couldn't unwrap a function with alloc_size.
122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123 if (!E->getType()->isPointerType())
124 return nullptr;
125
126 E = E->IgnoreParens();
127 // If we're doing a variable assignment from e.g. malloc(N), there will
128 // probably be a cast of some kind. Ignore it.
129 if (const auto *Cast = dyn_cast<CastExpr>(E))
130 E = Cast->getSubExpr()->IgnoreParens();
131
132 if (const auto *CE = dyn_cast<CallExpr>(E))
133 return getAllocSizeAttr(CE) ? CE : nullptr;
134 return nullptr;
135 }
136
137 /// Determines whether or not the given Base contains a call to a function
138 /// with the alloc_size attribute.
139 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
140 const auto *E = Base.dyn_cast<const Expr *>();
141 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
142 }
143
144 /// Determines if an LValue with the given LValueBase will have an unsized
145 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000146 /// Find the path length and type of the most-derived subobject in the given
147 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000148 static unsigned
149 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
150 ArrayRef<APValue::LValuePathEntry> Path,
Martin Bohme542c84b2017-08-30 10:44:46 +0000151 uint64_t &ArraySize, QualType &Type, bool &IsArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000152 // This only accepts LValueBases from APValues, and APValues don't support
153 // arrays that lack size info.
154 assert(!isBaseAnAllocSizeCall(Base) &&
155 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000156 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000157 Type = getType(Base);
158
Richard Smith80815602011-11-07 05:07:52 +0000159 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000160 if (Type->isArrayType()) {
Martin Bohme542c84b2017-08-30 10:44:46 +0000161 const ConstantArrayType *CAT =
162 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
163 Type = CAT->getElementType();
164 ArraySize = CAT->getSize().getZExtValue();
Richard Smitha8105bc2012-01-06 16:39:00 +0000165 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000166 IsArray = true;
Richard Smith66c96992012-02-18 22:04:06 +0000167 } else if (Type->isAnyComplexType()) {
168 const ComplexType *CT = Type->castAs<ComplexType>();
169 Type = CT->getElementType();
170 ArraySize = 2;
171 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000172 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000173 } else if (const FieldDecl *FD = getAsField(Path[I])) {
174 Type = FD->getType();
175 ArraySize = 0;
176 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000177 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000178 } else {
Richard Smith80815602011-11-07 05:07:52 +0000179 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000180 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000181 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000182 }
Richard Smith80815602011-11-07 05:07:52 +0000183 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000184 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000185 }
186
Richard Smitha8105bc2012-01-06 16:39:00 +0000187 // The order of this enum is important for diagnostics.
188 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000189 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000190 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000191 };
192
Richard Smith96e0c102011-11-04 02:25:55 +0000193 /// A path from a glvalue to a subobject of that glvalue.
194 struct SubobjectDesignator {
195 /// True if the subobject was named in a manner not supported by C++11. Such
196 /// lvalues can still be folded, but they are not core constant expressions
197 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000198 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000199
Richard Smitha8105bc2012-01-06 16:39:00 +0000200 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000201 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000202
Daniel Jasperffdee092017-05-02 19:21:42 +0000203 /// Indicator of whether the first entry is an unsized array.
204 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000205
George Burgess IVa51c4072015-10-16 01:49:01 +0000206 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000207 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000208
Richard Smitha8105bc2012-01-06 16:39:00 +0000209 /// The length of the path to the most-derived object of which this is a
210 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000211 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000212
George Burgess IVa51c4072015-10-16 01:49:01 +0000213 /// The size of the array of which the most-derived object is an element.
214 /// This will always be 0 if the most-derived object is not an array
215 /// element. 0 is not an indicator of whether or not the most-derived object
216 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000217 ///
218 /// If the current array is an unsized array, the value of this is
219 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000220 uint64_t MostDerivedArraySize;
221
222 /// The type of the most derived object referred to by this address.
223 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000224
Richard Smith80815602011-11-07 05:07:52 +0000225 typedef APValue::LValuePathEntry PathEntry;
226
Richard Smith96e0c102011-11-04 02:25:55 +0000227 /// The entries on the path from the glvalue to the designated subobject.
228 SmallVector<PathEntry, 8> Entries;
229
Richard Smitha8105bc2012-01-06 16:39:00 +0000230 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000231
Richard Smitha8105bc2012-01-06 16:39:00 +0000232 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000233 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000234 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000235 MostDerivedPathLength(0), MostDerivedArraySize(0),
236 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000237
238 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000239 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000240 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000241 MostDerivedPathLength(0), MostDerivedArraySize(0) {
242 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000243 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000244 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000245 ArrayRef<PathEntry> VEntries = V.getLValuePath();
246 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000247 if (V.getLValueBase()) {
248 bool IsArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000249 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000250 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Martin Bohme542c84b2017-08-30 10:44:46 +0000251 MostDerivedType, IsArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000252 MostDerivedIsArrayElement = IsArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000253 }
Richard Smith80815602011-11-07 05:07:52 +0000254 }
255 }
256
Richard Smith96e0c102011-11-04 02:25:55 +0000257 void setInvalid() {
258 Invalid = true;
259 Entries.clear();
260 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000261
George Burgess IVe3763372016-12-22 02:50:20 +0000262 /// Determine whether the most derived subobject is an array without a
263 /// known bound.
264 bool isMostDerivedAnUnsizedArray() const {
265 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000266 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000267 }
268
269 /// Determine what the most derived array's size is. Results in an assertion
270 /// failure if the most derived array lacks a size.
271 uint64_t getMostDerivedArraySize() const {
272 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
273 return MostDerivedArraySize;
274 }
275
Richard Smitha8105bc2012-01-06 16:39:00 +0000276 /// Determine whether this is a one-past-the-end pointer.
277 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000278 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000279 if (IsOnePastTheEnd)
280 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000281 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000282 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
283 return true;
284 return false;
285 }
286
287 /// Check that this refers to a valid subobject.
288 bool isValidSubobject() const {
289 if (Invalid)
290 return false;
291 return !isOnePastTheEnd();
292 }
293 /// Check that this refers to a valid subobject, and if not, produce a
294 /// relevant diagnostic and set the designator as invalid.
295 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
296
297 /// Update this designator to refer to the first element within this array.
298 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000299 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000300 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000301 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000302
303 // This is a most-derived object.
304 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000305 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000306 MostDerivedArraySize = CAT->getSize().getZExtValue();
307 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000308 }
George Burgess IVe3763372016-12-22 02:50:20 +0000309 /// Update this designator to refer to the first element within the array of
310 /// elements of type T. This is an array of unknown size.
311 void addUnsizedArrayUnchecked(QualType ElemTy) {
312 PathEntry Entry;
313 Entry.ArrayIndex = 0;
314 Entries.push_back(Entry);
315
316 MostDerivedType = ElemTy;
317 MostDerivedIsArrayElement = true;
318 // The value in MostDerivedArraySize is undefined in this case. So, set it
319 // to an arbitrary value that's likely to loudly break things if it's
320 // used.
Martin Bohme542c84b2017-08-30 10:44:46 +0000321 MostDerivedArraySize = std::numeric_limits<uint64_t>::max() / 2;
George Burgess IVe3763372016-12-22 02:50:20 +0000322 MostDerivedPathLength = Entries.size();
323 }
Richard Smith96e0c102011-11-04 02:25:55 +0000324 /// Update this designator to refer to the given base or member of this
325 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000326 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000327 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000328 APValue::BaseOrMemberType Value(D, Virtual);
329 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000330 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000331
332 // If this isn't a base class, it's a new most-derived object.
333 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
334 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000335 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000336 MostDerivedArraySize = 0;
337 MostDerivedPathLength = Entries.size();
338 }
Richard Smith96e0c102011-11-04 02:25:55 +0000339 }
Richard Smith66c96992012-02-18 22:04:06 +0000340 /// Update this designator to refer to the given complex component.
341 void addComplexUnchecked(QualType EltTy, bool Imag) {
342 PathEntry Entry;
343 Entry.ArrayIndex = Imag;
344 Entries.push_back(Entry);
345
346 // This is technically a most-derived object, though in practice this
347 // is unlikely to matter.
348 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000349 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000350 MostDerivedArraySize = 2;
351 MostDerivedPathLength = Entries.size();
352 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000353 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
354 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000355 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000356 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
357 if (Invalid || !N) return;
358 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
359 if (isMostDerivedAnUnsizedArray()) {
360 // Can't verify -- trust that the user is doing the right thing (or if
361 // not, trust that the caller will catch the bad behavior).
362 // FIXME: Should we reject if this overflows, at least?
363 Entries.back().ArrayIndex += TruncatedN;
364 return;
365 }
366
367 // [expr.add]p4: For the purposes of these operators, a pointer to a
368 // nonarray object behaves the same as a pointer to the first element of
369 // an array of length one with the type of the object as its element type.
370 bool IsArray = MostDerivedPathLength == Entries.size() &&
371 MostDerivedIsArrayElement;
372 uint64_t ArrayIndex =
373 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
374 uint64_t ArraySize =
375 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
376
377 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
378 // Calculate the actual index in a wide enough type, so we can include
379 // it in the note.
380 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
381 (llvm::APInt&)N += ArrayIndex;
382 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
383 diagnosePointerArithmetic(Info, E, N);
384 setInvalid();
385 return;
386 }
387
388 ArrayIndex += TruncatedN;
389 assert(ArrayIndex <= ArraySize &&
390 "bounds check succeeded for out-of-bounds index");
391
392 if (IsArray)
393 Entries.back().ArrayIndex = ArrayIndex;
394 else
395 IsOnePastTheEnd = (ArrayIndex != 0);
396 }
Richard Smith96e0c102011-11-04 02:25:55 +0000397 };
398
Richard Smith254a73d2011-10-28 22:34:42 +0000399 /// A stack frame in the constexpr call stack.
400 struct CallStackFrame {
401 EvalInfo &Info;
402
403 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000404 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000405
Richard Smithf6f003a2011-12-16 19:06:07 +0000406 /// Callee - The function which was called.
407 const FunctionDecl *Callee;
408
Richard Smithd62306a2011-11-10 06:34:14 +0000409 /// This - The binding for the this pointer in this call, if any.
410 const LValue *This;
411
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000412 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000413 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000414 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000415
Eli Friedman4830ec82012-06-25 21:21:08 +0000416 // Note that we intentionally use std::map here so that references to
417 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000418 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000419 typedef MapTy::const_iterator temp_iterator;
420 /// Temporaries - Temporary lvalues materialized within this stack frame.
421 MapTy Temporaries;
422
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000423 /// CallLoc - The location of the call expression for this call.
424 SourceLocation CallLoc;
425
426 /// Index - The call index of this call.
427 unsigned Index;
428
Faisal Vali051e3a22017-02-16 04:12:21 +0000429 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
430 // on the overall stack usage of deeply-recursing constexpr evaluataions.
431 // (We should cache this map rather than recomputing it repeatedly.)
432 // But let's try this and see how it goes; we can look into caching the map
433 // as a later change.
434
435 /// LambdaCaptureFields - Mapping from captured variables/this to
436 /// corresponding data members in the closure class.
437 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
438 FieldDecl *LambdaThisCaptureField;
439
Richard Smithf6f003a2011-12-16 19:06:07 +0000440 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
441 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000442 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000443 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000444
445 APValue *getTemporary(const void *Key) {
446 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000447 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000448 }
449 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000450 };
451
Richard Smith852c9db2013-04-20 22:23:05 +0000452 /// Temporarily override 'this'.
453 class ThisOverrideRAII {
454 public:
455 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
456 : Frame(Frame), OldThis(Frame.This) {
457 if (Enable)
458 Frame.This = NewThis;
459 }
460 ~ThisOverrideRAII() {
461 Frame.This = OldThis;
462 }
463 private:
464 CallStackFrame &Frame;
465 const LValue *OldThis;
466 };
467
Richard Smith92b1ce02011-12-12 09:28:41 +0000468 /// A partial diagnostic which we might know in advance that we are not going
469 /// to emit.
470 class OptionalDiagnostic {
471 PartialDiagnostic *Diag;
472
473 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000474 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
475 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000476
477 template<typename T>
478 OptionalDiagnostic &operator<<(const T &v) {
479 if (Diag)
480 *Diag << v;
481 return *this;
482 }
Richard Smithfe800032012-01-31 04:08:20 +0000483
484 OptionalDiagnostic &operator<<(const APSInt &I) {
485 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000486 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000487 I.toString(Buffer);
488 *Diag << StringRef(Buffer.data(), Buffer.size());
489 }
490 return *this;
491 }
492
493 OptionalDiagnostic &operator<<(const APFloat &F) {
494 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000495 // FIXME: Force the precision of the source value down so we don't
496 // print digits which are usually useless (we don't really care here if
497 // we truncate a digit by accident in edge cases). Ideally,
Daniel Jasperffdee092017-05-02 19:21:42 +0000498 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000499 // representation which rounds to the correct value, but it's a bit
500 // tricky to implement.
501 unsigned precision =
502 llvm::APFloat::semanticsPrecision(F.getSemantics());
503 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000504 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000505 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000506 *Diag << StringRef(Buffer.data(), Buffer.size());
507 }
508 return *this;
509 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000510 };
511
Richard Smith08d6a2c2013-07-24 07:11:57 +0000512 /// A cleanup, and a flag indicating whether it is lifetime-extended.
513 class Cleanup {
514 llvm::PointerIntPair<APValue*, 1, bool> Value;
515
516 public:
517 Cleanup(APValue *Val, bool IsLifetimeExtended)
518 : Value(Val, IsLifetimeExtended) {}
519
520 bool isLifetimeExtended() const { return Value.getInt(); }
521 void endLifetime() {
522 *Value.getPointer() = APValue();
523 }
524 };
525
Richard Smithb228a862012-02-15 02:18:13 +0000526 /// EvalInfo - This is a private struct used by the evaluator to capture
527 /// information about a subexpression as it is folded. It retains information
528 /// about the AST context, but also maintains information about the folded
529 /// expression.
530 ///
531 /// If an expression could be evaluated, it is still possible it is not a C
532 /// "integer constant expression" or constant expression. If not, this struct
533 /// captures information about how and why not.
534 ///
535 /// One bit of information passed *into* the request for constant folding
536 /// indicates whether the subexpression is "evaluated" or not according to C
537 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
538 /// evaluate the expression regardless of what the RHS is, but C only allows
539 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000540 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000541 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000542
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000543 /// EvalStatus - Contains information about the evaluation.
544 Expr::EvalStatus &EvalStatus;
545
546 /// CurrentCall - The top of the constexpr call stack.
547 CallStackFrame *CurrentCall;
548
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000549 /// CallStackDepth - The number of calls in the call stack right now.
550 unsigned CallStackDepth;
551
Richard Smithb228a862012-02-15 02:18:13 +0000552 /// NextCallIndex - The next call index to assign.
553 unsigned NextCallIndex;
554
Richard Smitha3d3bd22013-05-08 02:12:03 +0000555 /// StepsLeft - The remaining number of evaluation steps we're permitted
556 /// to perform. This is essentially a limit for the number of statements
557 /// we will evaluate.
558 unsigned StepsLeft;
559
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000560 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000561 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000562 CallStackFrame BottomFrame;
563
Richard Smith08d6a2c2013-07-24 07:11:57 +0000564 /// A stack of values whose lifetimes end at the end of some surrounding
565 /// evaluation frame.
566 llvm::SmallVector<Cleanup, 16> CleanupStack;
567
Richard Smithd62306a2011-11-10 06:34:14 +0000568 /// EvaluatingDecl - This is the declaration whose initializer is being
569 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000570 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000571
572 /// EvaluatingDeclValue - This is the value being constructed for the
573 /// declaration whose initializer is being evaluated, if any.
574 APValue *EvaluatingDeclValue;
575
Erik Pilkington42925492017-10-04 00:18:55 +0000576 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
577 /// the call index that that lvalue was allocated in.
578 typedef std::pair<APValue::LValueBase, unsigned> EvaluatingObject;
579
580 /// EvaluatingConstructors - Set of objects that are currently being
581 /// constructed.
582 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
583
584 struct EvaluatingConstructorRAII {
585 EvalInfo &EI;
586 EvaluatingObject Object;
587 bool DidInsert;
588 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
589 : EI(EI), Object(Object) {
590 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
591 }
592 ~EvaluatingConstructorRAII() {
593 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
594 }
595 };
596
597 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex) {
598 return EvaluatingConstructors.count(EvaluatingObject(Decl, CallIndex));
599 }
600
Richard Smith410306b2016-12-12 02:53:20 +0000601 /// The current array initialization index, if we're performing array
602 /// initialization.
603 uint64_t ArrayInitIndex = -1;
604
Richard Smith357362d2011-12-13 06:39:58 +0000605 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
606 /// notes attached to it will also be stored, otherwise they will not be.
607 bool HasActiveDiagnostic;
608
Richard Smith0c6124b2015-12-03 01:36:22 +0000609 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
610 /// fold (not just why it's not strictly a constant expression)?
611 bool HasFoldFailureDiagnostic;
612
George Burgess IV8c892b52016-05-25 22:31:54 +0000613 /// \brief Whether or not we're currently speculatively evaluating.
614 bool IsSpeculativelyEvaluating;
615
Richard Smith6d4c6582013-11-05 22:18:15 +0000616 enum EvaluationMode {
617 /// Evaluate as a constant expression. Stop if we find that the expression
618 /// is not a constant expression.
619 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000620
Richard Smith6d4c6582013-11-05 22:18:15 +0000621 /// Evaluate as a potential constant expression. Keep going if we hit a
622 /// construct that we can't evaluate yet (because we don't yet know the
623 /// value of something) but stop if we hit something that could never be
624 /// a constant expression.
625 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000626
Richard Smith6d4c6582013-11-05 22:18:15 +0000627 /// Fold the expression to a constant. Stop if we hit a side-effect that
628 /// we can't model.
629 EM_ConstantFold,
630
631 /// Evaluate the expression looking for integer overflow and similar
632 /// issues. Don't worry about side-effects, and try to visit all
633 /// subexpressions.
634 EM_EvaluateForOverflow,
635
636 /// Evaluate in any way we know how. Don't worry about side-effects that
637 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000638 EM_IgnoreSideEffects,
639
640 /// Evaluate as a constant expression. Stop if we find that the expression
641 /// is not a constant expression. Some expressions can be retried in the
642 /// optimizer if we don't constant fold them here, but in an unevaluated
643 /// context we try to fold them immediately since the optimizer never
644 /// gets a chance to look at it.
645 EM_ConstantExpressionUnevaluated,
646
647 /// Evaluate as a potential constant expression. Keep going if we hit a
648 /// construct that we can't evaluate yet (because we don't yet know the
649 /// value of something) but stop if we hit something that could never be
650 /// a constant expression. Some expressions can be retried in the
651 /// optimizer if we don't constant fold them here, but in an unevaluated
652 /// context we try to fold them immediately since the optimizer never
653 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000654 EM_PotentialConstantExpressionUnevaluated,
655
George Burgess IVf9013bf2017-02-10 22:52:29 +0000656 /// Evaluate as a constant expression. In certain scenarios, if:
657 /// - we find a MemberExpr with a base that can't be evaluated, or
658 /// - we find a variable initialized with a call to a function that has
659 /// the alloc_size attribute on it
660 /// then we may consider evaluation to have succeeded.
661 ///
George Burgess IVe3763372016-12-22 02:50:20 +0000662 /// In either case, the LValue returned shall have an invalid base; in the
663 /// former, the base will be the invalid MemberExpr, in the latter, the
664 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
665 /// said CallExpr.
666 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000667 } EvalMode;
668
669 /// Are we checking whether the expression is a potential constant
670 /// expression?
671 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000672 return EvalMode == EM_PotentialConstantExpression ||
673 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000674 }
675
676 /// Are we checking an expression for overflow?
677 // FIXME: We should check for any kind of undefined or suspicious behavior
678 // in such constructs, not just overflow.
679 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
680
681 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000682 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000683 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000684 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000685 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
686 EvaluatingDecl((const ValueDecl *)nullptr),
687 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000688 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
689 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000690
Richard Smith7525ff62013-05-09 07:14:00 +0000691 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
692 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000693 EvaluatingDeclValue = &Value;
Erik Pilkington42925492017-10-04 00:18:55 +0000694 EvaluatingConstructors.insert({Base, 0});
Richard Smithd62306a2011-11-10 06:34:14 +0000695 }
696
David Blaikiebbafb8a2012-03-11 07:00:24 +0000697 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000698
Richard Smith357362d2011-12-13 06:39:58 +0000699 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000700 // Don't perform any constexpr calls (other than the call we're checking)
701 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000702 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000703 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000704 if (NextCallIndex == 0) {
705 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000706 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000707 return false;
708 }
Richard Smith357362d2011-12-13 06:39:58 +0000709 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
710 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000711 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000712 << getLangOpts().ConstexprCallDepth;
713 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000714 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000715
Richard Smithb228a862012-02-15 02:18:13 +0000716 CallStackFrame *getCallFrame(unsigned CallIndex) {
717 assert(CallIndex && "no call index in getCallFrame");
718 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
719 // be null in this loop.
720 CallStackFrame *Frame = CurrentCall;
721 while (Frame->Index > CallIndex)
722 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000723 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000724 }
725
Richard Smitha3d3bd22013-05-08 02:12:03 +0000726 bool nextStep(const Stmt *S) {
727 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000728 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000729 return false;
730 }
731 --StepsLeft;
732 return true;
733 }
734
Richard Smith357362d2011-12-13 06:39:58 +0000735 private:
736 /// Add a diagnostic to the diagnostics list.
737 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
738 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
739 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
740 return EvalStatus.Diag->back().second;
741 }
742
Richard Smithf6f003a2011-12-16 19:06:07 +0000743 /// Add notes containing a call stack to the current point of evaluation.
744 void addCallStack(unsigned Limit);
745
Faisal Valie690b7a2016-07-02 22:34:24 +0000746 private:
747 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
748 unsigned ExtraNotes, bool IsCCEDiag) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000749
Richard Smith92b1ce02011-12-12 09:28:41 +0000750 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000751 // If we have a prior diagnostic, it will be noting that the expression
752 // isn't a constant expression. This diagnostic is more important,
753 // unless we require this evaluation to produce a constant expression.
754 //
755 // FIXME: We might want to show both diagnostics to the user in
756 // EM_ConstantFold mode.
757 if (!EvalStatus.Diag->empty()) {
758 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000759 case EM_ConstantFold:
760 case EM_IgnoreSideEffects:
761 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000762 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000763 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000764 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000765 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000766 case EM_ConstantExpression:
767 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000768 case EM_ConstantExpressionUnevaluated:
769 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000770 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000771 HasActiveDiagnostic = false;
772 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000773 }
774 }
775
Richard Smithf6f003a2011-12-16 19:06:07 +0000776 unsigned CallStackNotes = CallStackDepth - 1;
777 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
778 if (Limit)
779 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000780 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000781 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000782
Richard Smith357362d2011-12-13 06:39:58 +0000783 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000784 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000785 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000786 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
787 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000788 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000789 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000790 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000791 }
Richard Smith357362d2011-12-13 06:39:58 +0000792 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000793 return OptionalDiagnostic();
794 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000795 public:
796 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
797 OptionalDiagnostic
798 FFDiag(SourceLocation Loc,
799 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
800 unsigned ExtraNotes = 0) {
801 return Diag(Loc, DiagId, ExtraNotes, false);
802 }
Daniel Jasperffdee092017-05-02 19:21:42 +0000803
Faisal Valie690b7a2016-07-02 22:34:24 +0000804 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000805 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000806 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000807 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000808 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000809 HasActiveDiagnostic = false;
810 return OptionalDiagnostic();
811 }
812
Richard Smith92b1ce02011-12-12 09:28:41 +0000813 /// Diagnose that the evaluation does not produce a C++11 core constant
814 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000815 ///
816 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
817 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000818 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000819 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000820 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000821 // Don't override a previous diagnostic. Don't bother collecting
822 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000823 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000824 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000825 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000826 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000827 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000828 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000829 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
830 = diag::note_invalid_subexpr_in_const_expr,
831 unsigned ExtraNotes = 0) {
832 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
833 }
Richard Smith357362d2011-12-13 06:39:58 +0000834 /// Add a note to a prior diagnostic.
835 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
836 if (!HasActiveDiagnostic)
837 return OptionalDiagnostic();
838 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000839 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000840
841 /// Add a stack of notes to a prior diagnostic.
842 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
843 if (HasActiveDiagnostic) {
844 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
845 Diags.begin(), Diags.end());
846 }
847 }
Richard Smith253c2a32012-01-27 01:14:48 +0000848
Richard Smith6d4c6582013-11-05 22:18:15 +0000849 /// Should we continue evaluation after encountering a side-effect that we
850 /// couldn't model?
851 bool keepEvaluatingAfterSideEffect() {
852 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000853 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000854 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000855 case EM_EvaluateForOverflow:
856 case EM_IgnoreSideEffects:
857 return true;
858
Richard Smith6d4c6582013-11-05 22:18:15 +0000859 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000860 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000861 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000862 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000863 return false;
864 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000865 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000866 }
867
868 /// Note that we have had a side-effect, and determine whether we should
869 /// keep evaluating.
870 bool noteSideEffect() {
871 EvalStatus.HasSideEffects = true;
872 return keepEvaluatingAfterSideEffect();
873 }
874
Richard Smithce8eca52015-12-08 03:21:47 +0000875 /// Should we continue evaluation after encountering undefined behavior?
876 bool keepEvaluatingAfterUndefinedBehavior() {
877 switch (EvalMode) {
878 case EM_EvaluateForOverflow:
879 case EM_IgnoreSideEffects:
880 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000881 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000882 return true;
883
884 case EM_PotentialConstantExpression:
885 case EM_PotentialConstantExpressionUnevaluated:
886 case EM_ConstantExpression:
887 case EM_ConstantExpressionUnevaluated:
888 return false;
889 }
890 llvm_unreachable("Missed EvalMode case");
891 }
892
893 /// Note that we hit something that was technically undefined behavior, but
894 /// that we can evaluate past it (such as signed overflow or floating-point
895 /// division by zero.)
896 bool noteUndefinedBehavior() {
897 EvalStatus.HasUndefinedBehavior = true;
898 return keepEvaluatingAfterUndefinedBehavior();
899 }
900
Richard Smith253c2a32012-01-27 01:14:48 +0000901 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000902 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000903 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000904 if (!StepsLeft)
905 return false;
906
907 switch (EvalMode) {
908 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000909 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000910 case EM_EvaluateForOverflow:
911 return true;
912
913 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000914 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000915 case EM_ConstantFold:
916 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000917 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000918 return false;
919 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000920 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000921 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000922
George Burgess IV8c892b52016-05-25 22:31:54 +0000923 /// Notes that we failed to evaluate an expression that other expressions
924 /// directly depend on, and determine if we should keep evaluating. This
925 /// should only be called if we actually intend to keep evaluating.
926 ///
927 /// Call noteSideEffect() instead if we may be able to ignore the value that
928 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
929 ///
930 /// (Foo(), 1) // use noteSideEffect
931 /// (Foo() || true) // use noteSideEffect
932 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000933 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000934 // Failure when evaluating some expression often means there is some
935 // subexpression whose evaluation was skipped. Therefore, (because we
936 // don't track whether we skipped an expression when unwinding after an
937 // evaluation failure) every evaluation failure that bubbles up from a
938 // subexpression implies that a side-effect has potentially happened. We
939 // skip setting the HasSideEffects flag to true until we decide to
940 // continue evaluating after that point, which happens here.
941 bool KeepGoing = keepEvaluatingAfterFailure();
942 EvalStatus.HasSideEffects |= KeepGoing;
943 return KeepGoing;
944 }
945
Richard Smith410306b2016-12-12 02:53:20 +0000946 class ArrayInitLoopIndex {
947 EvalInfo &Info;
948 uint64_t OuterIndex;
949
950 public:
951 ArrayInitLoopIndex(EvalInfo &Info)
952 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
953 Info.ArrayInitIndex = 0;
954 }
955 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
956
957 operator uint64_t&() { return Info.ArrayInitIndex; }
958 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000959 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000960
961 /// Object used to treat all foldable expressions as constant expressions.
962 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000963 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000964 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000965 bool HadNoPriorDiags;
966 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000967
Richard Smith6d4c6582013-11-05 22:18:15 +0000968 explicit FoldConstant(EvalInfo &Info, bool Enabled)
969 : Info(Info),
970 Enabled(Enabled),
971 HadNoPriorDiags(Info.EvalStatus.Diag &&
972 Info.EvalStatus.Diag->empty() &&
973 !Info.EvalStatus.HasSideEffects),
974 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000975 if (Enabled &&
976 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
977 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000978 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000979 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000980 void keepDiagnostics() { Enabled = false; }
981 ~FoldConstant() {
982 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000983 !Info.EvalStatus.HasSideEffects)
984 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000985 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000986 }
987 };
Richard Smith17100ba2012-02-16 02:46:34 +0000988
George Burgess IV3a03fab2015-09-04 21:28:13 +0000989 /// RAII object used to treat the current evaluation as the correct pointer
990 /// offset fold for the current EvalMode
991 struct FoldOffsetRAII {
992 EvalInfo &Info;
993 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +0000994 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +0000995 : Info(Info), OldMode(Info.EvalMode) {
996 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +0000997 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000998 }
999
1000 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1001 };
1002
George Burgess IV8c892b52016-05-25 22:31:54 +00001003 /// RAII object used to optionally suppress diagnostics and side-effects from
1004 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001005 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001006 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001007 Expr::EvalStatus OldStatus;
1008 bool OldIsSpeculativelyEvaluating;
Richard Smith17100ba2012-02-16 02:46:34 +00001009
George Burgess IV8c892b52016-05-25 22:31:54 +00001010 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001011 Info = Other.Info;
1012 OldStatus = Other.OldStatus;
Daniel Jaspera7e061f2017-08-17 06:33:46 +00001013 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001014 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001015 }
1016
1017 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001018 if (!Info)
1019 return;
1020
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001021 Info->EvalStatus = OldStatus;
1022 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
George Burgess IV8c892b52016-05-25 22:31:54 +00001023 }
1024
Richard Smith17100ba2012-02-16 02:46:34 +00001025 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001026 SpeculativeEvaluationRAII() = default;
1027
1028 SpeculativeEvaluationRAII(
1029 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001030 : Info(&Info), OldStatus(Info.EvalStatus),
1031 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
Richard Smith17100ba2012-02-16 02:46:34 +00001032 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001033 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001034 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001035
1036 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1037 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1038 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001039 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001040
1041 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1042 maybeRestoreState();
1043 moveFromAndCancel(std::move(Other));
1044 return *this;
1045 }
1046
1047 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001048 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001049
1050 /// RAII object wrapping a full-expression or block scope, and handling
1051 /// the ending of the lifetime of temporaries created within it.
1052 template<bool IsFullExpression>
1053 class ScopeRAII {
1054 EvalInfo &Info;
1055 unsigned OldStackSize;
1056 public:
1057 ScopeRAII(EvalInfo &Info)
1058 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1059 ~ScopeRAII() {
1060 // Body moved to a static method to encourage the compiler to inline away
1061 // instances of this class.
1062 cleanup(Info, OldStackSize);
1063 }
1064 private:
1065 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1066 unsigned NewEnd = OldStackSize;
1067 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1068 I != N; ++I) {
1069 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1070 // Full-expression cleanup of a lifetime-extended temporary: nothing
1071 // to do, just move this cleanup to the right place in the stack.
1072 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1073 ++NewEnd;
1074 } else {
1075 // End the lifetime of the object.
1076 Info.CleanupStack[I].endLifetime();
1077 }
1078 }
1079 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1080 Info.CleanupStack.end());
1081 }
1082 };
1083 typedef ScopeRAII<false> BlockScopeRAII;
1084 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001085}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001086
Richard Smitha8105bc2012-01-06 16:39:00 +00001087bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1088 CheckSubobjectKind CSK) {
1089 if (Invalid)
1090 return false;
1091 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001092 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001093 << CSK;
1094 setInvalid();
1095 return false;
1096 }
1097 return true;
1098}
1099
1100void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001101 const Expr *E,
1102 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001103 // If we're complaining, we must be able to statically determine the size of
1104 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001105 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001106 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001107 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001108 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001109 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001110 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001111 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001112 setInvalid();
1113}
1114
Richard Smithf6f003a2011-12-16 19:06:07 +00001115CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1116 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001117 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001118 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1119 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001120 Info.CurrentCall = this;
1121 ++Info.CallStackDepth;
1122}
1123
1124CallStackFrame::~CallStackFrame() {
1125 assert(Info.CurrentCall == this && "calls retired out of order");
1126 --Info.CallStackDepth;
1127 Info.CurrentCall = Caller;
1128}
1129
Richard Smith08d6a2c2013-07-24 07:11:57 +00001130APValue &CallStackFrame::createTemporary(const void *Key,
1131 bool IsLifetimeExtended) {
1132 APValue &Result = Temporaries[Key];
1133 assert(Result.isUninit() && "temporary created multiple times");
1134 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1135 return Result;
1136}
1137
Richard Smith84401042013-06-03 05:03:02 +00001138static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001139
1140void EvalInfo::addCallStack(unsigned Limit) {
1141 // Determine which calls to skip, if any.
1142 unsigned ActiveCalls = CallStackDepth - 1;
1143 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1144 if (Limit && Limit < ActiveCalls) {
1145 SkipStart = Limit / 2 + Limit % 2;
1146 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001147 }
1148
Richard Smithf6f003a2011-12-16 19:06:07 +00001149 // Walk the call stack and add the diagnostics.
1150 unsigned CallIdx = 0;
1151 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1152 Frame = Frame->Caller, ++CallIdx) {
1153 // Skip this call?
1154 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1155 if (CallIdx == SkipStart) {
1156 // Note that we're skipping calls.
1157 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1158 << unsigned(ActiveCalls - Limit);
1159 }
1160 continue;
1161 }
1162
Richard Smith5179eb72016-06-28 19:03:57 +00001163 // Use a different note for an inheriting constructor, because from the
1164 // user's perspective it's not really a function at all.
1165 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1166 if (CD->isInheritingConstructor()) {
1167 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1168 << CD->getParent();
1169 continue;
1170 }
1171 }
1172
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001173 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001174 llvm::raw_svector_ostream Out(Buffer);
1175 describeCall(Frame, Out);
1176 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1177 }
1178}
1179
1180namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001181 struct ComplexValue {
1182 private:
1183 bool IsInt;
1184
1185 public:
1186 APSInt IntReal, IntImag;
1187 APFloat FloatReal, FloatImag;
1188
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001189 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001190
1191 void makeComplexFloat() { IsInt = false; }
1192 bool isComplexFloat() const { return !IsInt; }
1193 APFloat &getComplexFloatReal() { return FloatReal; }
1194 APFloat &getComplexFloatImag() { return FloatImag; }
1195
1196 void makeComplexInt() { IsInt = true; }
1197 bool isComplexInt() const { return IsInt; }
1198 APSInt &getComplexIntReal() { return IntReal; }
1199 APSInt &getComplexIntImag() { return IntImag; }
1200
Richard Smith2e312c82012-03-03 22:46:17 +00001201 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001202 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001203 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001204 else
Richard Smith2e312c82012-03-03 22:46:17 +00001205 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001206 }
Richard Smith2e312c82012-03-03 22:46:17 +00001207 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001208 assert(v.isComplexFloat() || v.isComplexInt());
1209 if (v.isComplexFloat()) {
1210 makeComplexFloat();
1211 FloatReal = v.getComplexFloatReal();
1212 FloatImag = v.getComplexFloatImag();
1213 } else {
1214 makeComplexInt();
1215 IntReal = v.getComplexIntReal();
1216 IntImag = v.getComplexIntImag();
1217 }
1218 }
John McCall93d91dc2010-05-07 17:22:02 +00001219 };
John McCall45d55e42010-05-07 21:00:08 +00001220
1221 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001222 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001223 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001224 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001225 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001226 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001227 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001228
Richard Smithce40ad62011-11-12 22:28:03 +00001229 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001230 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001231 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001232 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001233 SubobjectDesignator &getLValueDesignator() { return Designator; }
1234 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001235 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001236
Richard Smith2e312c82012-03-03 22:46:17 +00001237 void moveInto(APValue &V) const {
1238 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001239 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1240 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001241 else {
1242 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Martin Bohme542c84b2017-08-30 10:44:46 +00001243 assert(!Designator.FirstEntryIsAnUnsizedArray &&
1244 "Unsized array with a valid base?");
Richard Smith2e312c82012-03-03 22:46:17 +00001245 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001246 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001247 }
John McCall45d55e42010-05-07 21:00:08 +00001248 }
Richard Smith2e312c82012-03-03 22:46:17 +00001249 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001250 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001251 Base = V.getLValueBase();
1252 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001253 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001254 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001255 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001256 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001257 }
1258
Tim Northover01503332017-05-26 02:16:00 +00001259 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001260#ifndef NDEBUG
1261 // We only allow a few types of invalid bases. Enforce that here.
1262 if (BInvalid) {
1263 const auto *E = B.get<const Expr *>();
1264 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1265 "Unexpected type of invalid base");
1266 }
1267#endif
1268
Richard Smithce40ad62011-11-12 22:28:03 +00001269 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001270 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001271 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001272 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001273 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001274 IsNullPtr = false;
1275 }
1276
1277 void setNull(QualType PointerTy, uint64_t TargetVal) {
1278 Base = (Expr *)nullptr;
1279 Offset = CharUnits::fromQuantity(TargetVal);
1280 InvalidBase = false;
1281 CallIndex = 0;
1282 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1283 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001284 }
1285
George Burgess IV3a03fab2015-09-04 21:28:13 +00001286 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1287 set(B, I, true);
1288 }
1289
Richard Smitha8105bc2012-01-06 16:39:00 +00001290 // Check that this LValue is not based on a null pointer. If it is, produce
1291 // a diagnostic and mark the designator as invalid.
1292 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1293 CheckSubobjectKind CSK) {
1294 if (Designator.Invalid)
1295 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001296 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001297 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001298 << CSK;
1299 Designator.setInvalid();
1300 return false;
1301 }
1302 return true;
1303 }
1304
1305 // Check this LValue refers to an object. If not, set the designator to be
1306 // invalid and emit a diagnostic.
1307 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001308 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001309 Designator.checkSubobject(Info, E, CSK);
1310 }
1311
1312 void addDecl(EvalInfo &Info, const Expr *E,
1313 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001314 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1315 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001316 }
Martin Bohme542c84b2017-08-30 10:44:46 +00001317 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1318 assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1319 assert(isBaseAnAllocSizeCall(Base) &&
1320 "Only alloc_size bases can have unsized arrays");
Daniel Jasperffdee092017-05-02 19:21:42 +00001321 Designator.FirstEntryIsAnUnsizedArray = true;
1322 Designator.addUnsizedArrayUnchecked(ElemTy);
George Burgess IVe3763372016-12-22 02:50:20 +00001323 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001324 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001325 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1326 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001327 }
Richard Smith66c96992012-02-18 22:04:06 +00001328 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001329 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1330 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001331 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001332 void clearIsNullPointer() {
1333 IsNullPtr = false;
1334 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001335 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1336 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001337 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1338 // but we're not required to diagnose it and it's valid in C++.)
1339 if (!Index)
1340 return;
1341
1342 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1343 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1344 // offsets.
1345 uint64_t Offset64 = Offset.getQuantity();
1346 uint64_t ElemSize64 = ElementSize.getQuantity();
1347 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1348 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1349
1350 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001351 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001352 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001353 }
1354 void adjustOffset(CharUnits N) {
1355 Offset += N;
1356 if (N.getQuantity())
1357 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001358 }
John McCall45d55e42010-05-07 21:00:08 +00001359 };
Richard Smith027bf112011-11-17 22:56:20 +00001360
1361 struct MemberPtr {
1362 MemberPtr() {}
1363 explicit MemberPtr(const ValueDecl *Decl) :
1364 DeclAndIsDerivedMember(Decl, false), Path() {}
1365
1366 /// The member or (direct or indirect) field referred to by this member
1367 /// pointer, or 0 if this is a null member pointer.
1368 const ValueDecl *getDecl() const {
1369 return DeclAndIsDerivedMember.getPointer();
1370 }
1371 /// Is this actually a member of some type derived from the relevant class?
1372 bool isDerivedMember() const {
1373 return DeclAndIsDerivedMember.getInt();
1374 }
1375 /// Get the class which the declaration actually lives in.
1376 const CXXRecordDecl *getContainingRecord() const {
1377 return cast<CXXRecordDecl>(
1378 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1379 }
1380
Richard Smith2e312c82012-03-03 22:46:17 +00001381 void moveInto(APValue &V) const {
1382 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001383 }
Richard Smith2e312c82012-03-03 22:46:17 +00001384 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001385 assert(V.isMemberPointer());
1386 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1387 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1388 Path.clear();
1389 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1390 Path.insert(Path.end(), P.begin(), P.end());
1391 }
1392
1393 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1394 /// whether the member is a member of some class derived from the class type
1395 /// of the member pointer.
1396 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1397 /// Path - The path of base/derived classes from the member declaration's
1398 /// class (exclusive) to the class type of the member pointer (inclusive).
1399 SmallVector<const CXXRecordDecl*, 4> Path;
1400
1401 /// Perform a cast towards the class of the Decl (either up or down the
1402 /// hierarchy).
1403 bool castBack(const CXXRecordDecl *Class) {
1404 assert(!Path.empty());
1405 const CXXRecordDecl *Expected;
1406 if (Path.size() >= 2)
1407 Expected = Path[Path.size() - 2];
1408 else
1409 Expected = getContainingRecord();
1410 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1411 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1412 // if B does not contain the original member and is not a base or
1413 // derived class of the class containing the original member, the result
1414 // of the cast is undefined.
1415 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1416 // (D::*). We consider that to be a language defect.
1417 return false;
1418 }
1419 Path.pop_back();
1420 return true;
1421 }
1422 /// Perform a base-to-derived member pointer cast.
1423 bool castToDerived(const CXXRecordDecl *Derived) {
1424 if (!getDecl())
1425 return true;
1426 if (!isDerivedMember()) {
1427 Path.push_back(Derived);
1428 return true;
1429 }
1430 if (!castBack(Derived))
1431 return false;
1432 if (Path.empty())
1433 DeclAndIsDerivedMember.setInt(false);
1434 return true;
1435 }
1436 /// Perform a derived-to-base member pointer cast.
1437 bool castToBase(const CXXRecordDecl *Base) {
1438 if (!getDecl())
1439 return true;
1440 if (Path.empty())
1441 DeclAndIsDerivedMember.setInt(true);
1442 if (isDerivedMember()) {
1443 Path.push_back(Base);
1444 return true;
1445 }
1446 return castBack(Base);
1447 }
1448 };
Richard Smith357362d2011-12-13 06:39:58 +00001449
Richard Smith7bb00672012-02-01 01:42:44 +00001450 /// Compare two member pointers, which are assumed to be of the same type.
1451 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1452 if (!LHS.getDecl() || !RHS.getDecl())
1453 return !LHS.getDecl() && !RHS.getDecl();
1454 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1455 return false;
1456 return LHS.Path == RHS.Path;
1457 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001458}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001459
Richard Smith2e312c82012-03-03 22:46:17 +00001460static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001461static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1462 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001463 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001464static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1465 bool InvalidBaseOK = false);
1466static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1467 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001468static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1469 EvalInfo &Info);
1470static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001471static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001472static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001473 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001474static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001475static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001476static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1477 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001478static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001479
1480//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001481// Misc utilities
1482//===----------------------------------------------------------------------===//
1483
Richard Smithd6cc1982017-01-31 02:23:02 +00001484/// Negate an APSInt in place, converting it to a signed form if necessary, and
1485/// preserving its value (by extending by up to one bit as needed).
1486static void negateAsSigned(APSInt &Int) {
1487 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1488 Int = Int.extend(Int.getBitWidth() + 1);
1489 Int.setIsSigned(true);
1490 }
1491 Int = -Int;
1492}
1493
Richard Smith84401042013-06-03 05:03:02 +00001494/// Produce a string describing the given constexpr call.
1495static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1496 unsigned ArgIndex = 0;
1497 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1498 !isa<CXXConstructorDecl>(Frame->Callee) &&
1499 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1500
1501 if (!IsMemberCall)
1502 Out << *Frame->Callee << '(';
1503
1504 if (Frame->This && IsMemberCall) {
1505 APValue Val;
1506 Frame->This->moveInto(Val);
1507 Val.printPretty(Out, Frame->Info.Ctx,
1508 Frame->This->Designator.MostDerivedType);
1509 // FIXME: Add parens around Val if needed.
1510 Out << "->" << *Frame->Callee << '(';
1511 IsMemberCall = false;
1512 }
1513
1514 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1515 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1516 if (ArgIndex > (unsigned)IsMemberCall)
1517 Out << ", ";
1518
1519 const ParmVarDecl *Param = *I;
1520 const APValue &Arg = Frame->Arguments[ArgIndex];
1521 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1522
1523 if (ArgIndex == 0 && IsMemberCall)
1524 Out << "->" << *Frame->Callee << '(';
1525 }
1526
1527 Out << ')';
1528}
1529
Richard Smithd9f663b2013-04-22 15:31:51 +00001530/// Evaluate an expression to see if it had side-effects, and discard its
1531/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001532/// \return \c true if the caller should keep evaluating.
1533static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001534 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001535 if (!Evaluate(Scratch, Info, E))
1536 // We don't need the value, but we might have skipped a side effect here.
1537 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001538 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001539}
1540
Richard Smithd62306a2011-11-10 06:34:14 +00001541/// Should this call expression be treated as a string literal?
1542static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001543 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001544 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1545 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1546}
1547
Richard Smithce40ad62011-11-12 22:28:03 +00001548static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001549 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1550 // constant expression of pointer type that evaluates to...
1551
1552 // ... a null pointer value, or a prvalue core constant expression of type
1553 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001554 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001555
Richard Smithce40ad62011-11-12 22:28:03 +00001556 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1557 // ... the address of an object with static storage duration,
1558 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1559 return VD->hasGlobalStorage();
1560 // ... the address of a function,
1561 return isa<FunctionDecl>(D);
1562 }
1563
1564 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001565 switch (E->getStmtClass()) {
1566 default:
1567 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001568 case Expr::CompoundLiteralExprClass: {
1569 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1570 return CLE->isFileScope() && CLE->isLValue();
1571 }
Richard Smithe6c01442013-06-05 00:46:14 +00001572 case Expr::MaterializeTemporaryExprClass:
1573 // A materialized temporary might have been lifetime-extended to static
1574 // storage duration.
1575 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001576 // A string literal has static storage duration.
1577 case Expr::StringLiteralClass:
1578 case Expr::PredefinedExprClass:
1579 case Expr::ObjCStringLiteralClass:
1580 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001581 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001582 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001583 return true;
1584 case Expr::CallExprClass:
1585 return IsStringLiteralCall(cast<CallExpr>(E));
1586 // For GCC compatibility, &&label has static storage duration.
1587 case Expr::AddrLabelExprClass:
1588 return true;
1589 // A Block literal expression may be used as the initialization value for
1590 // Block variables at global or local static scope.
1591 case Expr::BlockExprClass:
1592 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001593 case Expr::ImplicitValueInitExprClass:
1594 // FIXME:
1595 // We can never form an lvalue with an implicit value initialization as its
1596 // base through expression evaluation, so these only appear in one case: the
1597 // implicit variable declaration we invent when checking whether a constexpr
1598 // constructor can produce a constant expression. We must assume that such
1599 // an expression might be a global lvalue.
1600 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001601 }
John McCall95007602010-05-10 23:27:23 +00001602}
1603
Richard Smithb228a862012-02-15 02:18:13 +00001604static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1605 assert(Base && "no location for a null lvalue");
1606 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1607 if (VD)
1608 Info.Note(VD->getLocation(), diag::note_declared_at);
1609 else
Ted Kremenek28831752012-08-23 20:46:57 +00001610 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001611 diag::note_constexpr_temporary_here);
1612}
1613
Richard Smith80815602011-11-07 05:07:52 +00001614/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001615/// value for an address or reference constant expression. Return true if we
1616/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001617static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1618 QualType Type, const LValue &LVal) {
1619 bool IsReferenceType = Type->isReferenceType();
1620
Richard Smith357362d2011-12-13 06:39:58 +00001621 APValue::LValueBase Base = LVal.getLValueBase();
1622 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1623
Richard Smith0dea49e2012-02-18 04:58:18 +00001624 // Check that the object is a global. Note that the fake 'this' object we
1625 // manufacture when checking potential constant expressions is conservatively
1626 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001627 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001628 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001629 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001630 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001631 << IsReferenceType << !Designator.Entries.empty()
1632 << !!VD << VD;
1633 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001634 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001635 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001636 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001637 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001638 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001639 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001640 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001641 LVal.getLValueCallIndex() == 0) &&
1642 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001643
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001644 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1645 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001646 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001647 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001648 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001649
Hans Wennborg82dd8772014-06-25 22:19:48 +00001650 // A dllimport variable never acts like a constant.
1651 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001652 return false;
1653 }
1654 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1655 // __declspec(dllimport) must be handled very carefully:
1656 // We must never initialize an expression with the thunk in C++.
1657 // Doing otherwise would allow the same id-expression to yield
1658 // different addresses for the same function in different translation
1659 // units. However, this means that we must dynamically initialize the
1660 // expression with the contents of the import address table at runtime.
1661 //
1662 // The C language has no notion of ODR; furthermore, it has no notion of
1663 // dynamic initialization. This means that we are permitted to
1664 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001665 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001666 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001667 }
1668 }
1669
Richard Smitha8105bc2012-01-06 16:39:00 +00001670 // Allow address constant expressions to be past-the-end pointers. This is
1671 // an extension: the standard requires them to point to an object.
1672 if (!IsReferenceType)
1673 return true;
1674
1675 // A reference constant expression must refer to an object.
1676 if (!Base) {
1677 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001678 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001679 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001680 }
1681
Richard Smith357362d2011-12-13 06:39:58 +00001682 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001683 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001684 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001685 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001686 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001687 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001688 }
1689
Richard Smith80815602011-11-07 05:07:52 +00001690 return true;
1691}
1692
Reid Klecknercd016d82017-07-07 22:04:29 +00001693/// Member pointers are constant expressions unless they point to a
1694/// non-virtual dllimport member function.
1695static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1696 SourceLocation Loc,
1697 QualType Type,
1698 const APValue &Value) {
1699 const ValueDecl *Member = Value.getMemberPointerDecl();
1700 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1701 if (!FD)
1702 return true;
1703 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1704}
1705
Richard Smithfddd3842011-12-30 21:15:51 +00001706/// Check that this core constant expression is of literal type, and if not,
1707/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001708static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001709 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001710 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001711 return true;
1712
Richard Smith7525ff62013-05-09 07:14:00 +00001713 // C++1y: A constant initializer for an object o [...] may also invoke
1714 // constexpr constructors for o and its subobjects even if those objects
1715 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001716 //
1717 // C++11 missed this detail for aggregates, so classes like this:
1718 // struct foo_t { union { int i; volatile int j; } u; };
1719 // are not (obviously) initializable like so:
1720 // __attribute__((__require_constant_initialization__))
1721 // static const foo_t x = {{0}};
1722 // because "i" is a subobject with non-literal initialization (due to the
1723 // volatile member of the union). See:
1724 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1725 // Therefore, we use the C++1y behavior.
1726 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001727 return true;
1728
Richard Smithfddd3842011-12-30 21:15:51 +00001729 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001730 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001731 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001732 << E->getType();
1733 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001734 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001735 return false;
1736}
1737
Richard Smith0b0a0b62011-10-29 20:57:55 +00001738/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001739/// constant expression. If not, report an appropriate diagnostic. Does not
1740/// check that the expression is of literal type.
1741static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1742 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001743 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001744 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001745 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001746 return false;
1747 }
1748
Richard Smith77be48a2014-07-31 06:31:19 +00001749 // We allow _Atomic(T) to be initialized from anything that T can be
1750 // initialized from.
1751 if (const AtomicType *AT = Type->getAs<AtomicType>())
1752 Type = AT->getValueType();
1753
Richard Smithb228a862012-02-15 02:18:13 +00001754 // Core issue 1454: For a literal constant expression of array or class type,
1755 // each subobject of its value shall have been initialized by a constant
1756 // expression.
1757 if (Value.isArray()) {
1758 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1759 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1760 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1761 Value.getArrayInitializedElt(I)))
1762 return false;
1763 }
1764 if (!Value.hasArrayFiller())
1765 return true;
1766 return CheckConstantExpression(Info, DiagLoc, EltTy,
1767 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001768 }
Richard Smithb228a862012-02-15 02:18:13 +00001769 if (Value.isUnion() && Value.getUnionField()) {
1770 return CheckConstantExpression(Info, DiagLoc,
1771 Value.getUnionField()->getType(),
1772 Value.getUnionValue());
1773 }
1774 if (Value.isStruct()) {
1775 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1776 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1777 unsigned BaseIndex = 0;
1778 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1779 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1780 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1781 Value.getStructBase(BaseIndex)))
1782 return false;
1783 }
1784 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001785 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001786 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1787 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001788 return false;
1789 }
1790 }
1791
1792 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001793 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001794 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001795 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1796 }
1797
Reid Klecknercd016d82017-07-07 22:04:29 +00001798 if (Value.isMemberPointer())
1799 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1800
Richard Smithb228a862012-02-15 02:18:13 +00001801 // Everything else is fine.
1802 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001803}
1804
Benjamin Kramer8407df72015-03-09 16:47:52 +00001805static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001806 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001807}
1808
1809static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001810 if (Value.CallIndex)
1811 return false;
1812 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1813 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001814}
1815
Richard Smithcecf1842011-11-01 21:06:14 +00001816static bool IsWeakLValue(const LValue &Value) {
1817 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001818 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001819}
1820
David Majnemerb5116032014-12-09 23:32:34 +00001821static bool isZeroSized(const LValue &Value) {
1822 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001823 if (Decl && isa<VarDecl>(Decl)) {
1824 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001825 if (Ty->isArrayType())
1826 return Ty->isIncompleteType() ||
1827 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001828 }
1829 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001830}
1831
Richard Smith2e312c82012-03-03 22:46:17 +00001832static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001833 // A null base expression indicates a null pointer. These are always
1834 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001835 if (!Value.getLValueBase()) {
1836 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001837 return true;
1838 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001839
Richard Smith027bf112011-11-17 22:56:20 +00001840 // We have a non-null base. These are generally known to be true, but if it's
1841 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001842 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001843 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001844 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001845}
1846
Richard Smith2e312c82012-03-03 22:46:17 +00001847static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001848 switch (Val.getKind()) {
1849 case APValue::Uninitialized:
1850 return false;
1851 case APValue::Int:
1852 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001853 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001854 case APValue::Float:
1855 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001856 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001857 case APValue::ComplexInt:
1858 Result = Val.getComplexIntReal().getBoolValue() ||
1859 Val.getComplexIntImag().getBoolValue();
1860 return true;
1861 case APValue::ComplexFloat:
1862 Result = !Val.getComplexFloatReal().isZero() ||
1863 !Val.getComplexFloatImag().isZero();
1864 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001865 case APValue::LValue:
1866 return EvalPointerValueAsBool(Val, Result);
1867 case APValue::MemberPointer:
1868 Result = Val.getMemberPointerDecl();
1869 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001870 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001871 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001872 case APValue::Struct:
1873 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001874 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001875 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001876 }
1877
Richard Smith11562c52011-10-28 17:51:58 +00001878 llvm_unreachable("unknown APValue kind");
1879}
1880
1881static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1882 EvalInfo &Info) {
1883 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001884 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001885 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001886 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001887 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001888}
1889
Richard Smith357362d2011-12-13 06:39:58 +00001890template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001891static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001892 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001893 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001894 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001895 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001896}
1897
1898static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1899 QualType SrcType, const APFloat &Value,
1900 QualType DestType, APSInt &Result) {
1901 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001902 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001903 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001904
Richard Smith357362d2011-12-13 06:39:58 +00001905 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001906 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001907 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1908 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001909 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001910 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001911}
1912
Richard Smith357362d2011-12-13 06:39:58 +00001913static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1914 QualType SrcType, QualType DestType,
1915 APFloat &Result) {
1916 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001917 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001918 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1919 APFloat::rmNearestTiesToEven, &ignored)
1920 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001921 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001922 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001923}
1924
Richard Smith911e1422012-01-30 22:27:01 +00001925static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1926 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001927 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001928 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001929 APSInt Result = Value;
1930 // Figure out if this is a truncate, extend or noop cast.
1931 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001932 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001933 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001934 return Result;
1935}
1936
Richard Smith357362d2011-12-13 06:39:58 +00001937static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1938 QualType SrcType, const APSInt &Value,
1939 QualType DestType, APFloat &Result) {
1940 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1941 if (Result.convertFromAPInt(Value, Value.isSigned(),
1942 APFloat::rmNearestTiesToEven)
1943 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001944 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001945 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001946}
1947
Richard Smith49ca8aa2013-08-06 07:09:20 +00001948static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1949 APValue &Value, const FieldDecl *FD) {
1950 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1951
1952 if (!Value.isInt()) {
1953 // Trying to store a pointer-cast-to-integer into a bitfield.
1954 // FIXME: In this case, we should provide the diagnostic for casting
1955 // a pointer to an integer.
1956 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001957 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001958 return false;
1959 }
1960
1961 APSInt &Int = Value.getInt();
1962 unsigned OldBitWidth = Int.getBitWidth();
1963 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1964 if (NewBitWidth < OldBitWidth)
1965 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1966 return true;
1967}
1968
Eli Friedman803acb32011-12-22 03:51:45 +00001969static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1970 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001971 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001972 if (!Evaluate(SVal, Info, E))
1973 return false;
1974 if (SVal.isInt()) {
1975 Res = SVal.getInt();
1976 return true;
1977 }
1978 if (SVal.isFloat()) {
1979 Res = SVal.getFloat().bitcastToAPInt();
1980 return true;
1981 }
1982 if (SVal.isVector()) {
1983 QualType VecTy = E->getType();
1984 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1985 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1986 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1987 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1988 Res = llvm::APInt::getNullValue(VecSize);
1989 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1990 APValue &Elt = SVal.getVectorElt(i);
1991 llvm::APInt EltAsInt;
1992 if (Elt.isInt()) {
1993 EltAsInt = Elt.getInt();
1994 } else if (Elt.isFloat()) {
1995 EltAsInt = Elt.getFloat().bitcastToAPInt();
1996 } else {
1997 // Don't try to handle vectors of anything other than int or float
1998 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001999 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002000 return false;
2001 }
2002 unsigned BaseEltSize = EltAsInt.getBitWidth();
2003 if (BigEndian)
2004 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2005 else
2006 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2007 }
2008 return true;
2009 }
2010 // Give up if the input isn't an int, float, or vector. For example, we
2011 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002012 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002013 return false;
2014}
2015
Richard Smith43e77732013-05-07 04:50:00 +00002016/// Perform the given integer operation, which is known to need at most BitWidth
2017/// bits, and check for overflow in the original type (if that type was not an
2018/// unsigned type).
2019template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002020static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2021 const APSInt &LHS, const APSInt &RHS,
2022 unsigned BitWidth, Operation Op,
2023 APSInt &Result) {
2024 if (LHS.isUnsigned()) {
2025 Result = Op(LHS, RHS);
2026 return true;
2027 }
Richard Smith43e77732013-05-07 04:50:00 +00002028
2029 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002030 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002031 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002032 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002033 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002034 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002035 << Result.toString(10) << E->getType();
2036 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002037 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002038 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002039 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002040}
2041
2042/// Perform the given binary integer operation.
2043static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2044 BinaryOperatorKind Opcode, APSInt RHS,
2045 APSInt &Result) {
2046 switch (Opcode) {
2047 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002048 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002049 return false;
2050 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002051 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2052 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002053 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002054 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2055 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002056 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002057 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2058 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002059 case BO_And: Result = LHS & RHS; return true;
2060 case BO_Xor: Result = LHS ^ RHS; return true;
2061 case BO_Or: Result = LHS | RHS; return true;
2062 case BO_Div:
2063 case BO_Rem:
2064 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002065 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002066 return false;
2067 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002068 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2069 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2070 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002071 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2072 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002073 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2074 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002075 return true;
2076 case BO_Shl: {
2077 if (Info.getLangOpts().OpenCL)
2078 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2079 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2080 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2081 RHS.isUnsigned());
2082 else if (RHS.isSigned() && RHS.isNegative()) {
2083 // During constant-folding, a negative shift is an opposite shift. Such
2084 // a shift is not a constant expression.
2085 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2086 RHS = -RHS;
2087 goto shift_right;
2088 }
2089 shift_left:
2090 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2091 // the shifted type.
2092 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2093 if (SA != RHS) {
2094 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2095 << RHS << E->getType() << LHS.getBitWidth();
2096 } else if (LHS.isSigned()) {
2097 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2098 // operand, and must not overflow the corresponding unsigned type.
2099 if (LHS.isNegative())
2100 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2101 else if (LHS.countLeadingZeros() < SA)
2102 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2103 }
2104 Result = LHS << SA;
2105 return true;
2106 }
2107 case BO_Shr: {
2108 if (Info.getLangOpts().OpenCL)
2109 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2110 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2111 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2112 RHS.isUnsigned());
2113 else if (RHS.isSigned() && RHS.isNegative()) {
2114 // During constant-folding, a negative shift is an opposite shift. Such a
2115 // shift is not a constant expression.
2116 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2117 RHS = -RHS;
2118 goto shift_left;
2119 }
2120 shift_right:
2121 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2122 // shifted type.
2123 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2124 if (SA != RHS)
2125 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2126 << RHS << E->getType() << LHS.getBitWidth();
2127 Result = LHS >> SA;
2128 return true;
2129 }
2130
2131 case BO_LT: Result = LHS < RHS; return true;
2132 case BO_GT: Result = LHS > RHS; return true;
2133 case BO_LE: Result = LHS <= RHS; return true;
2134 case BO_GE: Result = LHS >= RHS; return true;
2135 case BO_EQ: Result = LHS == RHS; return true;
2136 case BO_NE: Result = LHS != RHS; return true;
2137 }
2138}
2139
Richard Smith861b5b52013-05-07 23:34:45 +00002140/// Perform the given binary floating-point operation, in-place, on LHS.
2141static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2142 APFloat &LHS, BinaryOperatorKind Opcode,
2143 const APFloat &RHS) {
2144 switch (Opcode) {
2145 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002146 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002147 return false;
2148 case BO_Mul:
2149 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2150 break;
2151 case BO_Add:
2152 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2153 break;
2154 case BO_Sub:
2155 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2156 break;
2157 case BO_Div:
2158 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2159 break;
2160 }
2161
Richard Smith0c6124b2015-12-03 01:36:22 +00002162 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002163 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002164 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002165 }
Richard Smith861b5b52013-05-07 23:34:45 +00002166 return true;
2167}
2168
Richard Smitha8105bc2012-01-06 16:39:00 +00002169/// Cast an lvalue referring to a base subobject to a derived class, by
2170/// truncating the lvalue's path to the given length.
2171static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2172 const RecordDecl *TruncatedType,
2173 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002174 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002175
2176 // Check we actually point to a derived class object.
2177 if (TruncatedElements == D.Entries.size())
2178 return true;
2179 assert(TruncatedElements >= D.MostDerivedPathLength &&
2180 "not casting to a derived class");
2181 if (!Result.checkSubobject(Info, E, CSK_Derived))
2182 return false;
2183
2184 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002185 const RecordDecl *RD = TruncatedType;
2186 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002187 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002188 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2189 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002190 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002191 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002192 else
Richard Smithd62306a2011-11-10 06:34:14 +00002193 Result.Offset -= Layout.getBaseClassOffset(Base);
2194 RD = Base;
2195 }
Richard Smith027bf112011-11-17 22:56:20 +00002196 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002197 return true;
2198}
2199
John McCalld7bca762012-05-01 00:38:49 +00002200static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002201 const CXXRecordDecl *Derived,
2202 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002203 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002204 if (!RL) {
2205 if (Derived->isInvalidDecl()) return false;
2206 RL = &Info.Ctx.getASTRecordLayout(Derived);
2207 }
2208
Richard Smithd62306a2011-11-10 06:34:14 +00002209 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002210 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002211 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002212}
2213
Richard Smitha8105bc2012-01-06 16:39:00 +00002214static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002215 const CXXRecordDecl *DerivedDecl,
2216 const CXXBaseSpecifier *Base) {
2217 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2218
John McCalld7bca762012-05-01 00:38:49 +00002219 if (!Base->isVirtual())
2220 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002221
Richard Smitha8105bc2012-01-06 16:39:00 +00002222 SubobjectDesignator &D = Obj.Designator;
2223 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002224 return false;
2225
Richard Smitha8105bc2012-01-06 16:39:00 +00002226 // Extract most-derived object and corresponding type.
2227 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2228 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2229 return false;
2230
2231 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002232 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002233 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2234 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002235 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002236 return true;
2237}
2238
Richard Smith84401042013-06-03 05:03:02 +00002239static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2240 QualType Type, LValue &Result) {
2241 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2242 PathE = E->path_end();
2243 PathI != PathE; ++PathI) {
2244 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2245 *PathI))
2246 return false;
2247 Type = (*PathI)->getType();
2248 }
2249 return true;
2250}
2251
Richard Smithd62306a2011-11-10 06:34:14 +00002252/// Update LVal to refer to the given field, which must be a member of the type
2253/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002254static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002255 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002256 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002257 if (!RL) {
2258 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002259 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002260 }
Richard Smithd62306a2011-11-10 06:34:14 +00002261
2262 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002263 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002264 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002265 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002266}
2267
Richard Smith1b78b3d2012-01-25 22:15:11 +00002268/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002269static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002270 LValue &LVal,
2271 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002272 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002273 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002274 return false;
2275 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002276}
2277
Richard Smithd62306a2011-11-10 06:34:14 +00002278/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002279static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2280 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002281 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2282 // extension.
2283 if (Type->isVoidType() || Type->isFunctionType()) {
2284 Size = CharUnits::One();
2285 return true;
2286 }
2287
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002288 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002289 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002290 return false;
2291 }
2292
Richard Smithd62306a2011-11-10 06:34:14 +00002293 if (!Type->isConstantSizeType()) {
2294 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002295 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002296 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002297 return false;
2298 }
2299
2300 Size = Info.Ctx.getTypeSizeInChars(Type);
2301 return true;
2302}
2303
2304/// Update a pointer value to model pointer arithmetic.
2305/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002306/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002307/// \param LVal - The pointer value to be updated.
2308/// \param EltTy - The pointee type represented by LVal.
2309/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002310static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2311 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002312 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002313 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002314 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002315 return false;
2316
Yaxun Liu402804b2016-12-15 08:09:08 +00002317 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002318 return true;
2319}
2320
Richard Smithd6cc1982017-01-31 02:23:02 +00002321static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2322 LValue &LVal, QualType EltTy,
2323 int64_t Adjustment) {
2324 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2325 APSInt::get(Adjustment));
2326}
2327
Richard Smith66c96992012-02-18 22:04:06 +00002328/// Update an lvalue to refer to a component of a complex number.
2329/// \param Info - Information about the ongoing evaluation.
2330/// \param LVal - The lvalue to be updated.
2331/// \param EltTy - The complex number's component type.
2332/// \param Imag - False for the real component, true for the imaginary.
2333static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2334 LValue &LVal, QualType EltTy,
2335 bool Imag) {
2336 if (Imag) {
2337 CharUnits SizeOfComponent;
2338 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2339 return false;
2340 LVal.Offset += SizeOfComponent;
2341 }
2342 LVal.addComplex(Info, E, EltTy, Imag);
2343 return true;
2344}
2345
Faisal Vali051e3a22017-02-16 04:12:21 +00002346static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2347 QualType Type, const LValue &LVal,
2348 APValue &RVal);
2349
Richard Smith27908702011-10-24 17:54:18 +00002350/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002351///
2352/// \param Info Information about the ongoing evaluation.
2353/// \param E An expression to be used when printing diagnostics.
2354/// \param VD The variable whose initializer should be obtained.
2355/// \param Frame The frame in which the variable was created. Must be null
2356/// if this variable is not local to the evaluation.
2357/// \param Result Filled in with a pointer to the value of the variable.
2358static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2359 const VarDecl *VD, CallStackFrame *Frame,
2360 APValue *&Result) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002361
Richard Smith254a73d2011-10-28 22:34:42 +00002362 // If this is a parameter to an active constexpr function call, perform
2363 // argument substitution.
2364 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002365 // Assume arguments of a potential constant expression are unknown
2366 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002367 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002368 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002369 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002370 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002371 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002372 }
Richard Smith3229b742013-05-05 21:17:10 +00002373 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002374 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002375 }
Richard Smith27908702011-10-24 17:54:18 +00002376
Richard Smithd9f663b2013-04-22 15:31:51 +00002377 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002378 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002379 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002380 if (!Result) {
2381 // Assume variables referenced within a lambda's call operator that were
2382 // not declared within the call operator are captures and during checking
2383 // of a potential constant expression, assume they are unknown constant
2384 // expressions.
2385 assert(isLambdaCallOperator(Frame->Callee) &&
2386 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2387 "missing value for local variable");
2388 if (Info.checkingPotentialConstantExpression())
2389 return false;
2390 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002391 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002392 diag::note_unimplemented_constexpr_lambda_feature_ast)
2393 << "captures not currently allowed";
2394 return false;
2395 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002396 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002397 }
2398
Richard Smithd0b4dd62011-12-19 06:19:21 +00002399 // Dig out the initializer, and use the declaration which it's attached to.
2400 const Expr *Init = VD->getAnyInitializer(VD);
2401 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002402 // If we're checking a potential constant expression, the variable could be
2403 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002404 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002405 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002406 return false;
2407 }
2408
Richard Smithd62306a2011-11-10 06:34:14 +00002409 // If we're currently evaluating the initializer of this declaration, use that
2410 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002411 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002412 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002413 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002414 }
2415
Richard Smithcecf1842011-11-01 21:06:14 +00002416 // Never evaluate the initializer of a weak variable. We can't be sure that
2417 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002418 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002419 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002420 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002421 }
Richard Smithcecf1842011-11-01 21:06:14 +00002422
Richard Smithd0b4dd62011-12-19 06:19:21 +00002423 // Check that we can fold the initializer. In C++, we will have already done
2424 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002425 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002426 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002427 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002428 Notes.size() + 1) << VD;
2429 Info.Note(VD->getLocation(), diag::note_declared_at);
2430 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002431 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002432 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002433 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002434 Notes.size() + 1) << VD;
2435 Info.Note(VD->getLocation(), diag::note_declared_at);
2436 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002437 }
Richard Smith27908702011-10-24 17:54:18 +00002438
Richard Smith3229b742013-05-05 21:17:10 +00002439 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002440 return true;
Richard Smith27908702011-10-24 17:54:18 +00002441}
2442
Richard Smith11562c52011-10-28 17:51:58 +00002443static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002444 Qualifiers Quals = T.getQualifiers();
2445 return Quals.hasConst() && !Quals.hasVolatile();
2446}
2447
Richard Smithe97cbd72011-11-11 04:05:33 +00002448/// Get the base index of the given base class within an APValue representing
2449/// the given derived class.
2450static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2451 const CXXRecordDecl *Base) {
2452 Base = Base->getCanonicalDecl();
2453 unsigned Index = 0;
2454 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2455 E = Derived->bases_end(); I != E; ++I, ++Index) {
2456 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2457 return Index;
2458 }
2459
2460 llvm_unreachable("base class missing from derived class's bases list");
2461}
2462
Richard Smith3da88fa2013-04-26 14:36:30 +00002463/// Extract the value of a character from a string literal.
2464static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2465 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002466 // FIXME: Support MakeStringConstant
2467 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2468 std::string Str;
2469 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2470 assert(Index <= Str.size() && "Index too large");
2471 return APSInt::getUnsigned(Str.c_str()[Index]);
2472 }
2473
Alexey Bataevec474782014-10-09 08:45:04 +00002474 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2475 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002476 const StringLiteral *S = cast<StringLiteral>(Lit);
2477 const ConstantArrayType *CAT =
2478 Info.Ctx.getAsConstantArrayType(S->getType());
2479 assert(CAT && "string literal isn't an array");
2480 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002481 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002482
2483 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002484 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002485 if (Index < S->getLength())
2486 Value = S->getCodeUnit(Index);
2487 return Value;
2488}
2489
Richard Smith3da88fa2013-04-26 14:36:30 +00002490// Expand a string literal into an array of characters.
2491static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2492 APValue &Result) {
2493 const StringLiteral *S = cast<StringLiteral>(Lit);
2494 const ConstantArrayType *CAT =
2495 Info.Ctx.getAsConstantArrayType(S->getType());
2496 assert(CAT && "string literal isn't an array");
2497 QualType CharType = CAT->getElementType();
2498 assert(CharType->isIntegerType() && "unexpected character type");
2499
2500 unsigned Elts = CAT->getSize().getZExtValue();
2501 Result = APValue(APValue::UninitArray(),
2502 std::min(S->getLength(), Elts), Elts);
2503 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2504 CharType->isUnsignedIntegerType());
2505 if (Result.hasArrayFiller())
2506 Result.getArrayFiller() = APValue(Value);
2507 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2508 Value = S->getCodeUnit(I);
2509 Result.getArrayInitializedElt(I) = APValue(Value);
2510 }
2511}
2512
2513// Expand an array so that it has more than Index filled elements.
2514static void expandArray(APValue &Array, unsigned Index) {
2515 unsigned Size = Array.getArraySize();
2516 assert(Index < Size);
2517
2518 // Always at least double the number of elements for which we store a value.
2519 unsigned OldElts = Array.getArrayInitializedElts();
2520 unsigned NewElts = std::max(Index+1, OldElts * 2);
2521 NewElts = std::min(Size, std::max(NewElts, 8u));
2522
2523 // Copy the data across.
2524 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2525 for (unsigned I = 0; I != OldElts; ++I)
2526 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2527 for (unsigned I = OldElts; I != NewElts; ++I)
2528 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2529 if (NewValue.hasArrayFiller())
2530 NewValue.getArrayFiller() = Array.getArrayFiller();
2531 Array.swap(NewValue);
2532}
2533
Richard Smithb01fe402014-09-16 01:24:02 +00002534/// Determine whether a type would actually be read by an lvalue-to-rvalue
2535/// conversion. If it's of class type, we may assume that the copy operation
2536/// is trivial. Note that this is never true for a union type with fields
2537/// (because the copy always "reads" the active member) and always true for
2538/// a non-class type.
2539static bool isReadByLvalueToRvalueConversion(QualType T) {
2540 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2541 if (!RD || (RD->isUnion() && !RD->field_empty()))
2542 return true;
2543 if (RD->isEmpty())
2544 return false;
2545
2546 for (auto *Field : RD->fields())
2547 if (isReadByLvalueToRvalueConversion(Field->getType()))
2548 return true;
2549
2550 for (auto &BaseSpec : RD->bases())
2551 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2552 return true;
2553
2554 return false;
2555}
2556
2557/// Diagnose an attempt to read from any unreadable field within the specified
2558/// type, which might be a class type.
2559static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2560 QualType T) {
2561 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2562 if (!RD)
2563 return false;
2564
2565 if (!RD->hasMutableFields())
2566 return false;
2567
2568 for (auto *Field : RD->fields()) {
2569 // If we're actually going to read this field in some way, then it can't
2570 // be mutable. If we're in a union, then assigning to a mutable field
2571 // (even an empty one) can change the active member, so that's not OK.
2572 // FIXME: Add core issue number for the union case.
2573 if (Field->isMutable() &&
2574 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002575 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002576 Info.Note(Field->getLocation(), diag::note_declared_at);
2577 return true;
2578 }
2579
2580 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2581 return true;
2582 }
2583
2584 for (auto &BaseSpec : RD->bases())
2585 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2586 return true;
2587
2588 // All mutable fields were empty, and thus not actually read.
2589 return false;
2590}
2591
Richard Smith861b5b52013-05-07 23:34:45 +00002592/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002593enum AccessKinds {
2594 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002595 AK_Assign,
2596 AK_Increment,
2597 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002598};
2599
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002600namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002601/// A handle to a complete object (an object that is not a subobject of
2602/// another object).
2603struct CompleteObject {
2604 /// The value of the complete object.
2605 APValue *Value;
2606 /// The type of the complete object.
2607 QualType Type;
2608
Craig Topper36250ad2014-05-12 05:36:57 +00002609 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002610 CompleteObject(APValue *Value, QualType Type)
2611 : Value(Value), Type(Type) {
2612 assert(Value && "missing value for complete object");
2613 }
2614
Aaron Ballman67347662015-02-15 22:00:28 +00002615 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002616};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002617} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002618
Richard Smith3da88fa2013-04-26 14:36:30 +00002619/// Find the designated sub-object of an rvalue.
2620template<typename SubobjectHandler>
2621typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002622findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002623 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002624 if (Sub.Invalid)
2625 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002626 return handler.failed();
Martin Bohme542c84b2017-08-30 10:44:46 +00002627 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002628 if (Info.getLangOpts().CPlusPlus11)
Martin Bohme542c84b2017-08-30 10:44:46 +00002629 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2630 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002631 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002632 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002633 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002634 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002635
Richard Smith3229b742013-05-05 21:17:10 +00002636 APValue *O = Obj.Value;
2637 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002638 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002639
Richard Smithd62306a2011-11-10 06:34:14 +00002640 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002641 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2642 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002643 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002644 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002645 return handler.failed();
2646 }
2647
Richard Smith49ca8aa2013-08-06 07:09:20 +00002648 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002649 // If we are reading an object of class type, there may still be more
2650 // things we need to check: if there are any mutable subobjects, we
2651 // cannot perform this read. (This only happens when performing a trivial
2652 // copy or assignment.)
2653 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2654 diagnoseUnreadableFields(Info, E, ObjType))
2655 return handler.failed();
2656
Richard Smith49ca8aa2013-08-06 07:09:20 +00002657 if (!handler.found(*O, ObjType))
2658 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002659
Richard Smith49ca8aa2013-08-06 07:09:20 +00002660 // If we modified a bit-field, truncate it to the right width.
2661 if (handler.AccessKind != AK_Read &&
2662 LastField && LastField->isBitField() &&
2663 !truncateBitfieldValue(Info, E, *O, LastField))
2664 return false;
2665
2666 return true;
2667 }
2668
Craig Topper36250ad2014-05-12 05:36:57 +00002669 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002670 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002671 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002672 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002673 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002674 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002675 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002676 // Note, it should not be possible to form a pointer with a valid
2677 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002678 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002679 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002680 << handler.AccessKind;
2681 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002682 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002683 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002684 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002685
2686 ObjType = CAT->getElementType();
2687
Richard Smith14a94132012-02-17 03:35:37 +00002688 // An array object is represented as either an Array APValue or as an
2689 // LValue which refers to a string literal.
2690 if (O->isLValue()) {
2691 assert(I == N - 1 && "extracting subobject of character?");
2692 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002693 if (handler.AccessKind != AK_Read)
2694 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2695 *O);
2696 else
2697 return handler.foundString(*O, ObjType, Index);
2698 }
2699
2700 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002701 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002702 else if (handler.AccessKind != AK_Read) {
2703 expandArray(*O, Index);
2704 O = &O->getArrayInitializedElt(Index);
2705 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002706 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002707 } else if (ObjType->isAnyComplexType()) {
2708 // Next subobject is a complex number.
2709 uint64_t Index = Sub.Entries[I].ArrayIndex;
2710 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002711 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002712 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002713 << handler.AccessKind;
2714 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002715 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002716 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002717 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002718
2719 bool WasConstQualified = ObjType.isConstQualified();
2720 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2721 if (WasConstQualified)
2722 ObjType.addConst();
2723
Richard Smith66c96992012-02-18 22:04:06 +00002724 assert(I == N - 1 && "extracting subobject of scalar?");
2725 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002726 return handler.found(Index ? O->getComplexIntImag()
2727 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002728 } else {
2729 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002730 return handler.found(Index ? O->getComplexFloatImag()
2731 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002732 }
Richard Smithd62306a2011-11-10 06:34:14 +00002733 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002734 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002735 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002736 << Field;
2737 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002738 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002739 }
2740
Richard Smithd62306a2011-11-10 06:34:14 +00002741 // Next subobject is a class, struct or union field.
2742 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2743 if (RD->isUnion()) {
2744 const FieldDecl *UnionField = O->getUnionField();
2745 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002746 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002747 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002748 << handler.AccessKind << Field << !UnionField << UnionField;
2749 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002750 }
Richard Smithd62306a2011-11-10 06:34:14 +00002751 O = &O->getUnionValue();
2752 } else
2753 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002754
2755 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002756 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002757 if (WasConstQualified && !Field->isMutable())
2758 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002759
2760 if (ObjType.isVolatileQualified()) {
2761 if (Info.getLangOpts().CPlusPlus) {
2762 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002763 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002764 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002765 Info.Note(Field->getLocation(), diag::note_declared_at);
2766 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002767 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002768 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002769 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002770 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002771
2772 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002773 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002774 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002775 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2776 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2777 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002778
2779 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002780 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002781 if (WasConstQualified)
2782 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002783 }
2784 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002785}
2786
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002787namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002788struct ExtractSubobjectHandler {
2789 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002790 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002791
2792 static const AccessKinds AccessKind = AK_Read;
2793
2794 typedef bool result_type;
2795 bool failed() { return false; }
2796 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002797 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002798 return true;
2799 }
2800 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002801 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002802 return true;
2803 }
2804 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002805 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002806 return true;
2807 }
2808 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002809 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002810 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2811 return true;
2812 }
2813};
Richard Smith3229b742013-05-05 21:17:10 +00002814} // end anonymous namespace
2815
Richard Smith3da88fa2013-04-26 14:36:30 +00002816const AccessKinds ExtractSubobjectHandler::AccessKind;
2817
2818/// Extract the designated sub-object of an rvalue.
2819static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002820 const CompleteObject &Obj,
2821 const SubobjectDesignator &Sub,
2822 APValue &Result) {
2823 ExtractSubobjectHandler Handler = { Info, Result };
2824 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002825}
2826
Richard Smith3229b742013-05-05 21:17:10 +00002827namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002828struct ModifySubobjectHandler {
2829 EvalInfo &Info;
2830 APValue &NewVal;
2831 const Expr *E;
2832
2833 typedef bool result_type;
2834 static const AccessKinds AccessKind = AK_Assign;
2835
2836 bool checkConst(QualType QT) {
2837 // Assigning to a const object has undefined behavior.
2838 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002839 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002840 return false;
2841 }
2842 return true;
2843 }
2844
2845 bool failed() { return false; }
2846 bool found(APValue &Subobj, QualType SubobjType) {
2847 if (!checkConst(SubobjType))
2848 return false;
2849 // We've been given ownership of NewVal, so just swap it in.
2850 Subobj.swap(NewVal);
2851 return true;
2852 }
2853 bool found(APSInt &Value, QualType SubobjType) {
2854 if (!checkConst(SubobjType))
2855 return false;
2856 if (!NewVal.isInt()) {
2857 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002858 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002859 return false;
2860 }
2861 Value = NewVal.getInt();
2862 return true;
2863 }
2864 bool found(APFloat &Value, QualType SubobjType) {
2865 if (!checkConst(SubobjType))
2866 return false;
2867 Value = NewVal.getFloat();
2868 return true;
2869 }
2870 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2871 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2872 }
2873};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002874} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002875
Richard Smith3229b742013-05-05 21:17:10 +00002876const AccessKinds ModifySubobjectHandler::AccessKind;
2877
Richard Smith3da88fa2013-04-26 14:36:30 +00002878/// Update the designated sub-object of an rvalue to the given value.
2879static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002880 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002881 const SubobjectDesignator &Sub,
2882 APValue &NewVal) {
2883 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002884 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002885}
2886
Richard Smith84f6dcf2012-02-02 01:16:57 +00002887/// Find the position where two subobject designators diverge, or equivalently
2888/// the length of the common initial subsequence.
2889static unsigned FindDesignatorMismatch(QualType ObjType,
2890 const SubobjectDesignator &A,
2891 const SubobjectDesignator &B,
2892 bool &WasArrayIndex) {
2893 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2894 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002895 if (!ObjType.isNull() &&
2896 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002897 // Next subobject is an array element.
2898 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2899 WasArrayIndex = true;
2900 return I;
2901 }
Richard Smith66c96992012-02-18 22:04:06 +00002902 if (ObjType->isAnyComplexType())
2903 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2904 else
2905 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002906 } else {
2907 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2908 WasArrayIndex = false;
2909 return I;
2910 }
2911 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2912 // Next subobject is a field.
2913 ObjType = FD->getType();
2914 else
2915 // Next subobject is a base class.
2916 ObjType = QualType();
2917 }
2918 }
2919 WasArrayIndex = false;
2920 return I;
2921}
2922
2923/// Determine whether the given subobject designators refer to elements of the
2924/// same array object.
2925static bool AreElementsOfSameArray(QualType ObjType,
2926 const SubobjectDesignator &A,
2927 const SubobjectDesignator &B) {
2928 if (A.Entries.size() != B.Entries.size())
2929 return false;
2930
George Burgess IVa51c4072015-10-16 01:49:01 +00002931 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002932 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2933 // A is a subobject of the array element.
2934 return false;
2935
2936 // If A (and B) designates an array element, the last entry will be the array
2937 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2938 // of length 1' case, and the entire path must match.
2939 bool WasArrayIndex;
2940 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2941 return CommonLength >= A.Entries.size() - IsArray;
2942}
2943
Richard Smith3229b742013-05-05 21:17:10 +00002944/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002945static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2946 AccessKinds AK, const LValue &LVal,
2947 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002948 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002949 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002950 return CompleteObject();
2951 }
2952
Craig Topper36250ad2014-05-12 05:36:57 +00002953 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002954 if (LVal.CallIndex) {
2955 Frame = Info.getCallFrame(LVal.CallIndex);
2956 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002957 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002958 << AK << LVal.Base.is<const ValueDecl*>();
2959 NoteLValueLocation(Info, LVal.Base);
2960 return CompleteObject();
2961 }
Richard Smith3229b742013-05-05 21:17:10 +00002962 }
2963
2964 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2965 // is not a constant expression (even if the object is non-volatile). We also
2966 // apply this rule to C++98, in order to conform to the expected 'volatile'
2967 // semantics.
2968 if (LValType.isVolatileQualified()) {
2969 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002970 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002971 << AK << LValType;
2972 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002973 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002974 return CompleteObject();
2975 }
2976
2977 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002978 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002979 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002980
2981 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2982 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2983 // In C++11, constexpr, non-volatile variables initialized with constant
2984 // expressions are constant expressions too. Inside constexpr functions,
2985 // parameters are constant expressions even if they're non-const.
2986 // In C++1y, objects local to a constant expression (those with a Frame) are
2987 // both readable and writable inside constant expressions.
2988 // In C, such things can also be folded, although they are not ICEs.
2989 const VarDecl *VD = dyn_cast<VarDecl>(D);
2990 if (VD) {
2991 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2992 VD = VDef;
2993 }
2994 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002995 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002996 return CompleteObject();
2997 }
2998
2999 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003000 if (BaseType.isVolatileQualified()) {
3001 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003002 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003003 << AK << 1 << VD;
3004 Info.Note(VD->getLocation(), diag::note_declared_at);
3005 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003006 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003007 }
3008 return CompleteObject();
3009 }
3010
3011 // Unless we're looking at a local variable or argument in a constexpr call,
3012 // the variable we're reading must be const.
3013 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003014 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003015 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3016 // OK, we can read and modify an object if we're in the process of
3017 // evaluating its initializer, because its lifetime began in this
3018 // evaluation.
3019 } else if (AK != AK_Read) {
3020 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003021 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003022 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003023 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003024 // OK, we can read this variable.
3025 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003026 // In OpenCL if a variable is in constant address space it is a const value.
3027 if (!(BaseType.isConstQualified() ||
3028 (Info.getLangOpts().OpenCL &&
3029 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003030 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003031 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003032 Info.Note(VD->getLocation(), diag::note_declared_at);
3033 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003034 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003035 }
3036 return CompleteObject();
3037 }
3038 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3039 // We support folding of const floating-point types, in order to make
3040 // static const data members of such types (supported as an extension)
3041 // more useful.
3042 if (Info.getLangOpts().CPlusPlus11) {
3043 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3044 Info.Note(VD->getLocation(), diag::note_declared_at);
3045 } else {
3046 Info.CCEDiag(E);
3047 }
George Burgess IVb5316982016-12-27 05:33:20 +00003048 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3049 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3050 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003051 } else {
3052 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003053 if (Info.checkingPotentialConstantExpression() &&
3054 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3055 // The definition of this variable could be constexpr. We can't
3056 // access it right now, but may be able to in future.
3057 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003058 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003059 Info.Note(VD->getLocation(), diag::note_declared_at);
3060 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003061 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003062 }
3063 return CompleteObject();
3064 }
3065 }
3066
3067 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3068 return CompleteObject();
3069 } else {
3070 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3071
3072 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003073 if (const MaterializeTemporaryExpr *MTE =
3074 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3075 assert(MTE->getStorageDuration() == SD_Static &&
3076 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003077
Richard Smithe6c01442013-06-05 00:46:14 +00003078 // Per C++1y [expr.const]p2:
3079 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3080 // - a [...] glvalue of integral or enumeration type that refers to
3081 // a non-volatile const object [...]
3082 // [...]
3083 // - a [...] glvalue of literal type that refers to a non-volatile
3084 // object whose lifetime began within the evaluation of e.
3085 //
3086 // C++11 misses the 'began within the evaluation of e' check and
3087 // instead allows all temporaries, including things like:
3088 // int &&r = 1;
3089 // int x = ++r;
3090 // constexpr int k = r;
3091 // Therefore we use the C++1y rules in C++11 too.
3092 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3093 const ValueDecl *ED = MTE->getExtendingDecl();
3094 if (!(BaseType.isConstQualified() &&
3095 BaseType->isIntegralOrEnumerationType()) &&
3096 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003097 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003098 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3099 return CompleteObject();
3100 }
3101
3102 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3103 assert(BaseVal && "got reference to unevaluated temporary");
3104 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003105 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003106 return CompleteObject();
3107 }
3108 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003109 BaseVal = Frame->getTemporary(Base);
3110 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003111 }
Richard Smith3229b742013-05-05 21:17:10 +00003112
3113 // Volatile temporary objects cannot be accessed in constant expressions.
3114 if (BaseType.isVolatileQualified()) {
3115 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003116 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003117 << AK << 0;
3118 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3119 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003120 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003121 }
3122 return CompleteObject();
3123 }
3124 }
3125
Richard Smith7525ff62013-05-09 07:14:00 +00003126 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003127 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003128 // object under construction.
Erik Pilkington42925492017-10-04 00:18:55 +00003129 if (Info.isEvaluatingConstructor(LVal.getLValueBase(), LVal.CallIndex)) {
Richard Smith7525ff62013-05-09 07:14:00 +00003130 BaseType = Info.Ctx.getCanonicalType(BaseType);
3131 BaseType.removeLocalConst();
3132 }
3133
Richard Smith6d4c6582013-11-05 22:18:15 +00003134 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003135 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003136 //
3137 // FIXME: Not all local state is mutable. Allow local constant subobjects
3138 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003139 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3140 Info.EvalStatus.HasSideEffects) ||
3141 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003142 return CompleteObject();
3143
3144 return CompleteObject(BaseVal, BaseType);
3145}
3146
Richard Smith243ef902013-05-05 23:31:59 +00003147/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3148/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3149/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003150///
3151/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003152/// \param Conv - The expression for which we are performing the conversion.
3153/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003154/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3155/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003156/// \param LVal - The glvalue on which we are attempting to perform this action.
3157/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003158static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003159 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003160 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003161 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003162 return false;
3163
Richard Smith3229b742013-05-05 21:17:10 +00003164 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003165 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003166 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003167 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3168 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3169 // initializer until now for such expressions. Such an expression can't be
3170 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003171 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003172 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003173 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003174 }
Richard Smith3229b742013-05-05 21:17:10 +00003175 APValue Lit;
3176 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3177 return false;
3178 CompleteObject LitObj(&Lit, Base->getType());
3179 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003180 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003181 // We represent a string literal array as an lvalue pointing at the
3182 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003183 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003184 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3185 CompleteObject StrObj(&Str, Base->getType());
3186 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003187 }
Richard Smith11562c52011-10-28 17:51:58 +00003188 }
3189
Richard Smith3229b742013-05-05 21:17:10 +00003190 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3191 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003192}
3193
3194/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003195static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003196 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003197 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003198 return false;
3199
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003200 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003201 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003202 return false;
3203 }
3204
Richard Smith3229b742013-05-05 21:17:10 +00003205 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3206 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00003207}
3208
Richard Smith243ef902013-05-05 23:31:59 +00003209static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3210 return T->isSignedIntegerType() &&
3211 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3212}
3213
3214namespace {
Richard Smith43e77732013-05-07 04:50:00 +00003215struct CompoundAssignSubobjectHandler {
3216 EvalInfo &Info;
3217 const Expr *E;
3218 QualType PromotedLHSType;
3219 BinaryOperatorKind Opcode;
3220 const APValue &RHS;
3221
3222 static const AccessKinds AccessKind = AK_Assign;
3223
3224 typedef bool result_type;
3225
3226 bool checkConst(QualType QT) {
3227 // Assigning to a const object has undefined behavior.
3228 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003229 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003230 return false;
3231 }
3232 return true;
3233 }
3234
3235 bool failed() { return false; }
3236 bool found(APValue &Subobj, QualType SubobjType) {
3237 switch (Subobj.getKind()) {
3238 case APValue::Int:
3239 return found(Subobj.getInt(), SubobjType);
3240 case APValue::Float:
3241 return found(Subobj.getFloat(), SubobjType);
3242 case APValue::ComplexInt:
3243 case APValue::ComplexFloat:
3244 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003245 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003246 return false;
3247 case APValue::LValue:
3248 return foundPointer(Subobj, SubobjType);
3249 default:
3250 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003251 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003252 return false;
3253 }
3254 }
3255 bool found(APSInt &Value, QualType SubobjType) {
3256 if (!checkConst(SubobjType))
3257 return false;
3258
3259 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3260 // We don't support compound assignment on integer-cast-to-pointer
3261 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003262 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003263 return false;
3264 }
3265
3266 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3267 SubobjType, Value);
3268 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3269 return false;
3270 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3271 return true;
3272 }
3273 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003274 return checkConst(SubobjType) &&
3275 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3276 Value) &&
3277 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3278 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003279 }
3280 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3281 if (!checkConst(SubobjType))
3282 return false;
3283
3284 QualType PointeeType;
3285 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3286 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003287
3288 if (PointeeType.isNull() || !RHS.isInt() ||
3289 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003290 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003291 return false;
3292 }
3293
Richard Smithd6cc1982017-01-31 02:23:02 +00003294 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003295 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003296 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003297
3298 LValue LVal;
3299 LVal.setFrom(Info.Ctx, Subobj);
3300 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3301 return false;
3302 LVal.moveInto(Subobj);
3303 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003304 }
3305 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3306 llvm_unreachable("shouldn't encounter string elements here");
3307 }
3308};
3309} // end anonymous namespace
3310
3311const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3312
3313/// Perform a compound assignment of LVal <op>= RVal.
3314static bool handleCompoundAssignment(
3315 EvalInfo &Info, const Expr *E,
3316 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3317 BinaryOperatorKind Opcode, const APValue &RVal) {
3318 if (LVal.Designator.Invalid)
3319 return false;
3320
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003321 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003322 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003323 return false;
3324 }
3325
3326 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3327 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3328 RVal };
3329 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3330}
3331
3332namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003333struct IncDecSubobjectHandler {
3334 EvalInfo &Info;
3335 const Expr *E;
3336 AccessKinds AccessKind;
3337 APValue *Old;
3338
3339 typedef bool result_type;
3340
3341 bool checkConst(QualType QT) {
3342 // Assigning to a const object has undefined behavior.
3343 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003344 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003345 return false;
3346 }
3347 return true;
3348 }
3349
3350 bool failed() { return false; }
3351 bool found(APValue &Subobj, QualType SubobjType) {
3352 // Stash the old value. Also clear Old, so we don't clobber it later
3353 // if we're post-incrementing a complex.
3354 if (Old) {
3355 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003356 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003357 }
3358
3359 switch (Subobj.getKind()) {
3360 case APValue::Int:
3361 return found(Subobj.getInt(), SubobjType);
3362 case APValue::Float:
3363 return found(Subobj.getFloat(), SubobjType);
3364 case APValue::ComplexInt:
3365 return found(Subobj.getComplexIntReal(),
3366 SubobjType->castAs<ComplexType>()->getElementType()
3367 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3368 case APValue::ComplexFloat:
3369 return found(Subobj.getComplexFloatReal(),
3370 SubobjType->castAs<ComplexType>()->getElementType()
3371 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3372 case APValue::LValue:
3373 return foundPointer(Subobj, SubobjType);
3374 default:
3375 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003376 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003377 return false;
3378 }
3379 }
3380 bool found(APSInt &Value, QualType SubobjType) {
3381 if (!checkConst(SubobjType))
3382 return false;
3383
3384 if (!SubobjType->isIntegerType()) {
3385 // We don't support increment / decrement on integer-cast-to-pointer
3386 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003387 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003388 return false;
3389 }
3390
3391 if (Old) *Old = APValue(Value);
3392
3393 // bool arithmetic promotes to int, and the conversion back to bool
3394 // doesn't reduce mod 2^n, so special-case it.
3395 if (SubobjType->isBooleanType()) {
3396 if (AccessKind == AK_Increment)
3397 Value = 1;
3398 else
3399 Value = !Value;
3400 return true;
3401 }
3402
3403 bool WasNegative = Value.isNegative();
3404 if (AccessKind == AK_Increment) {
3405 ++Value;
3406
3407 if (!WasNegative && Value.isNegative() &&
3408 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3409 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003410 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003411 }
3412 } else {
3413 --Value;
3414
3415 if (WasNegative && !Value.isNegative() &&
3416 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3417 unsigned BitWidth = Value.getBitWidth();
3418 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3419 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003420 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003421 }
3422 }
3423 return true;
3424 }
3425 bool found(APFloat &Value, QualType SubobjType) {
3426 if (!checkConst(SubobjType))
3427 return false;
3428
3429 if (Old) *Old = APValue(Value);
3430
3431 APFloat One(Value.getSemantics(), 1);
3432 if (AccessKind == AK_Increment)
3433 Value.add(One, APFloat::rmNearestTiesToEven);
3434 else
3435 Value.subtract(One, APFloat::rmNearestTiesToEven);
3436 return true;
3437 }
3438 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3439 if (!checkConst(SubobjType))
3440 return false;
3441
3442 QualType PointeeType;
3443 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3444 PointeeType = PT->getPointeeType();
3445 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003446 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003447 return false;
3448 }
3449
3450 LValue LVal;
3451 LVal.setFrom(Info.Ctx, Subobj);
3452 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3453 AccessKind == AK_Increment ? 1 : -1))
3454 return false;
3455 LVal.moveInto(Subobj);
3456 return true;
3457 }
3458 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3459 llvm_unreachable("shouldn't encounter string elements here");
3460 }
3461};
3462} // end anonymous namespace
3463
3464/// Perform an increment or decrement on LVal.
3465static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3466 QualType LValType, bool IsIncrement, APValue *Old) {
3467 if (LVal.Designator.Invalid)
3468 return false;
3469
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003470 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003471 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003472 return false;
3473 }
3474
3475 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3476 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3477 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3478 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3479}
3480
Richard Smithe97cbd72011-11-11 04:05:33 +00003481/// Build an lvalue for the object argument of a member function call.
3482static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3483 LValue &This) {
3484 if (Object->getType()->isPointerType())
3485 return EvaluatePointer(Object, This, Info);
3486
3487 if (Object->isGLValue())
3488 return EvaluateLValue(Object, This, Info);
3489
Richard Smithd9f663b2013-04-22 15:31:51 +00003490 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003491 return EvaluateTemporary(Object, This, Info);
3492
Faisal Valie690b7a2016-07-02 22:34:24 +00003493 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003494 return false;
3495}
3496
3497/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3498/// lvalue referring to the result.
3499///
3500/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003501/// \param LV - An lvalue referring to the base of the member pointer.
3502/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003503/// \param IncludeMember - Specifies whether the member itself is included in
3504/// the resulting LValue subobject designator. This is not possible when
3505/// creating a bound member function.
3506/// \return The field or method declaration to which the member pointer refers,
3507/// or 0 if evaluation fails.
3508static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003509 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003510 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003511 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003512 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003513 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003514 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003515 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003516
3517 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3518 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003519 if (!MemPtr.getDecl()) {
3520 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003521 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003522 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003523 }
Richard Smith253c2a32012-01-27 01:14:48 +00003524
Richard Smith027bf112011-11-17 22:56:20 +00003525 if (MemPtr.isDerivedMember()) {
3526 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003527 // The end of the derived-to-base path for the base object must match the
3528 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003529 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003530 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003531 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003532 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003533 }
Richard Smith027bf112011-11-17 22:56:20 +00003534 unsigned PathLengthToMember =
3535 LV.Designator.Entries.size() - MemPtr.Path.size();
3536 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3537 const CXXRecordDecl *LVDecl = getAsBaseClass(
3538 LV.Designator.Entries[PathLengthToMember + I]);
3539 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003540 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003541 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003542 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003543 }
Richard Smith027bf112011-11-17 22:56:20 +00003544 }
3545
3546 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003547 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003548 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003549 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003550 } else if (!MemPtr.Path.empty()) {
3551 // Extend the LValue path with the member pointer's path.
3552 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3553 MemPtr.Path.size() + IncludeMember);
3554
3555 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003556 if (const PointerType *PT = LVType->getAs<PointerType>())
3557 LVType = PT->getPointeeType();
3558 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3559 assert(RD && "member pointer access on non-class-type expression");
3560 // The first class in the path is that of the lvalue.
3561 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3562 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003563 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003564 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003565 RD = Base;
3566 }
3567 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003568 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3569 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003570 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003571 }
3572
3573 // Add the member. Note that we cannot build bound member functions here.
3574 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003575 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003576 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003577 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003578 } else if (const IndirectFieldDecl *IFD =
3579 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003580 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003581 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003582 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003583 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003584 }
Richard Smith027bf112011-11-17 22:56:20 +00003585 }
3586
3587 return MemPtr.getDecl();
3588}
3589
Richard Smith84401042013-06-03 05:03:02 +00003590static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3591 const BinaryOperator *BO,
3592 LValue &LV,
3593 bool IncludeMember = true) {
3594 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3595
3596 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003597 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003598 MemberPtr MemPtr;
3599 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3600 }
Craig Topper36250ad2014-05-12 05:36:57 +00003601 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003602 }
3603
3604 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3605 BO->getRHS(), IncludeMember);
3606}
3607
Richard Smith027bf112011-11-17 22:56:20 +00003608/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3609/// the provided lvalue, which currently refers to the base object.
3610static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3611 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003612 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003613 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003614 return false;
3615
Richard Smitha8105bc2012-01-06 16:39:00 +00003616 QualType TargetQT = E->getType();
3617 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3618 TargetQT = PT->getPointeeType();
3619
3620 // Check this cast lands within the final derived-to-base subobject path.
3621 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003622 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003623 << D.MostDerivedType << TargetQT;
3624 return false;
3625 }
3626
Richard Smith027bf112011-11-17 22:56:20 +00003627 // Check the type of the final cast. We don't need to check the path,
3628 // since a cast can only be formed if the path is unique.
3629 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003630 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3631 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003632 if (NewEntriesSize == D.MostDerivedPathLength)
3633 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3634 else
Richard Smith027bf112011-11-17 22:56:20 +00003635 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003636 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003637 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003638 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003639 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003640 }
Richard Smith027bf112011-11-17 22:56:20 +00003641
3642 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003643 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003644}
3645
Mike Stump876387b2009-10-27 22:09:17 +00003646namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003647enum EvalStmtResult {
3648 /// Evaluation failed.
3649 ESR_Failed,
3650 /// Hit a 'return' statement.
3651 ESR_Returned,
3652 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003653 ESR_Succeeded,
3654 /// Hit a 'continue' statement.
3655 ESR_Continue,
3656 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003657 ESR_Break,
3658 /// Still scanning for 'case' or 'default' statement.
3659 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003660};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003661}
Richard Smith254a73d2011-10-28 22:34:42 +00003662
Richard Smith97fcf4b2016-08-14 23:15:52 +00003663static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3664 // We don't need to evaluate the initializer for a static local.
3665 if (!VD->hasLocalStorage())
3666 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003667
Richard Smith97fcf4b2016-08-14 23:15:52 +00003668 LValue Result;
3669 Result.set(VD, Info.CurrentCall->Index);
3670 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003671
Richard Smith97fcf4b2016-08-14 23:15:52 +00003672 const Expr *InitE = VD->getInit();
3673 if (!InitE) {
3674 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3675 << false << VD->getType();
3676 Val = APValue();
3677 return false;
3678 }
Richard Smith51f03172013-06-20 03:00:05 +00003679
Richard Smith97fcf4b2016-08-14 23:15:52 +00003680 if (InitE->isValueDependent())
3681 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003682
Richard Smith97fcf4b2016-08-14 23:15:52 +00003683 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3684 // Wipe out any partially-computed value, to allow tracking that this
3685 // evaluation failed.
3686 Val = APValue();
3687 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003688 }
3689
3690 return true;
3691}
3692
Richard Smith97fcf4b2016-08-14 23:15:52 +00003693static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3694 bool OK = true;
3695
3696 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3697 OK &= EvaluateVarDecl(Info, VD);
3698
3699 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3700 for (auto *BD : DD->bindings())
3701 if (auto *VD = BD->getHoldingVar())
3702 OK &= EvaluateDecl(Info, VD);
3703
3704 return OK;
3705}
3706
3707
Richard Smith4e18ca52013-05-06 05:56:11 +00003708/// Evaluate a condition (either a variable declaration or an expression).
3709static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3710 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003711 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003712 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3713 return false;
3714 return EvaluateAsBooleanCondition(Cond, Result, Info);
3715}
3716
Richard Smith89210072016-04-04 23:29:43 +00003717namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003718/// \brief A location where the result (returned value) of evaluating a
3719/// statement should be stored.
3720struct StmtResult {
3721 /// The APValue that should be filled in with the returned value.
3722 APValue &Value;
3723 /// The location containing the result, if any (used to support RVO).
3724 const LValue *Slot;
3725};
Richard Smith89210072016-04-04 23:29:43 +00003726}
Richard Smith52a980a2015-08-28 02:43:42 +00003727
3728static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003729 const Stmt *S,
3730 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003731
3732/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003733static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003734 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003735 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003736 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003737 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003738 case ESR_Break:
3739 return ESR_Succeeded;
3740 case ESR_Succeeded:
3741 case ESR_Continue:
3742 return ESR_Continue;
3743 case ESR_Failed:
3744 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003745 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003746 return ESR;
3747 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003748 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003749}
3750
Richard Smith496ddcf2013-05-12 17:32:42 +00003751/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003752static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003753 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003754 BlockScopeRAII Scope(Info);
3755
Richard Smith496ddcf2013-05-12 17:32:42 +00003756 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003757 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003758 {
3759 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003760 if (const Stmt *Init = SS->getInit()) {
3761 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3762 if (ESR != ESR_Succeeded)
3763 return ESR;
3764 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003765 if (SS->getConditionVariable() &&
3766 !EvaluateDecl(Info, SS->getConditionVariable()))
3767 return ESR_Failed;
3768 if (!EvaluateInteger(SS->getCond(), Value, Info))
3769 return ESR_Failed;
3770 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003771
3772 // Find the switch case corresponding to the value of the condition.
3773 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003774 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003775 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3776 SC = SC->getNextSwitchCase()) {
3777 if (isa<DefaultStmt>(SC)) {
3778 Found = SC;
3779 continue;
3780 }
3781
3782 const CaseStmt *CS = cast<CaseStmt>(SC);
3783 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3784 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3785 : LHS;
3786 if (LHS <= Value && Value <= RHS) {
3787 Found = SC;
3788 break;
3789 }
3790 }
3791
3792 if (!Found)
3793 return ESR_Succeeded;
3794
3795 // Search the switch body for the switch case and evaluate it from there.
3796 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3797 case ESR_Break:
3798 return ESR_Succeeded;
3799 case ESR_Succeeded:
3800 case ESR_Continue:
3801 case ESR_Failed:
3802 case ESR_Returned:
3803 return ESR;
3804 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003805 // This can only happen if the switch case is nested within a statement
3806 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003807 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003808 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003809 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003810 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003811}
3812
Richard Smith254a73d2011-10-28 22:34:42 +00003813// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003814static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003815 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003816 if (!Info.nextStep(S))
3817 return ESR_Failed;
3818
Richard Smith496ddcf2013-05-12 17:32:42 +00003819 // If we're hunting down a 'case' or 'default' label, recurse through
3820 // substatements until we hit the label.
3821 if (Case) {
3822 // FIXME: We don't start the lifetime of objects whose initialization we
3823 // jump over. However, such objects must be of class type with a trivial
3824 // default constructor that initialize all subobjects, so must be empty,
3825 // so this almost never matters.
3826 switch (S->getStmtClass()) {
3827 case Stmt::CompoundStmtClass:
3828 // FIXME: Precompute which substatement of a compound statement we
3829 // would jump to, and go straight there rather than performing a
3830 // linear scan each time.
3831 case Stmt::LabelStmtClass:
3832 case Stmt::AttributedStmtClass:
3833 case Stmt::DoStmtClass:
3834 break;
3835
3836 case Stmt::CaseStmtClass:
3837 case Stmt::DefaultStmtClass:
3838 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003839 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003840 break;
3841
3842 case Stmt::IfStmtClass: {
3843 // FIXME: Precompute which side of an 'if' we would jump to, and go
3844 // straight there rather than scanning both sides.
3845 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003846
3847 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3848 // preceded by our switch label.
3849 BlockScopeRAII Scope(Info);
3850
Richard Smith496ddcf2013-05-12 17:32:42 +00003851 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3852 if (ESR != ESR_CaseNotFound || !IS->getElse())
3853 return ESR;
3854 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3855 }
3856
3857 case Stmt::WhileStmtClass: {
3858 EvalStmtResult ESR =
3859 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3860 if (ESR != ESR_Continue)
3861 return ESR;
3862 break;
3863 }
3864
3865 case Stmt::ForStmtClass: {
3866 const ForStmt *FS = cast<ForStmt>(S);
3867 EvalStmtResult ESR =
3868 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3869 if (ESR != ESR_Continue)
3870 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003871 if (FS->getInc()) {
3872 FullExpressionRAII IncScope(Info);
3873 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3874 return ESR_Failed;
3875 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003876 break;
3877 }
3878
3879 case Stmt::DeclStmtClass:
3880 // FIXME: If the variable has initialization that can't be jumped over,
3881 // bail out of any immediately-surrounding compound-statement too.
3882 default:
3883 return ESR_CaseNotFound;
3884 }
3885 }
3886
Richard Smith254a73d2011-10-28 22:34:42 +00003887 switch (S->getStmtClass()) {
3888 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003889 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003890 // Don't bother evaluating beyond an expression-statement which couldn't
3891 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003892 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003893 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003894 return ESR_Failed;
3895 return ESR_Succeeded;
3896 }
3897
Faisal Valie690b7a2016-07-02 22:34:24 +00003898 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003899 return ESR_Failed;
3900
3901 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003902 return ESR_Succeeded;
3903
Richard Smithd9f663b2013-04-22 15:31:51 +00003904 case Stmt::DeclStmtClass: {
3905 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003906 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003907 // Each declaration initialization is its own full-expression.
3908 // FIXME: This isn't quite right; if we're performing aggregate
3909 // initialization, each braced subexpression is its own full-expression.
3910 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003911 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003912 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003913 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003914 return ESR_Succeeded;
3915 }
3916
Richard Smith357362d2011-12-13 06:39:58 +00003917 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003918 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003919 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003920 if (RetExpr &&
3921 !(Result.Slot
3922 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3923 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003924 return ESR_Failed;
3925 return ESR_Returned;
3926 }
Richard Smith254a73d2011-10-28 22:34:42 +00003927
3928 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003929 BlockScopeRAII Scope(Info);
3930
Richard Smith254a73d2011-10-28 22:34:42 +00003931 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003932 for (const auto *BI : CS->body()) {
3933 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003934 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003935 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003936 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003937 return ESR;
3938 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003939 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003940 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003941
3942 case Stmt::IfStmtClass: {
3943 const IfStmt *IS = cast<IfStmt>(S);
3944
3945 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003946 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003947 if (const Stmt *Init = IS->getInit()) {
3948 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3949 if (ESR != ESR_Succeeded)
3950 return ESR;
3951 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003952 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003953 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003954 return ESR_Failed;
3955
3956 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3957 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3958 if (ESR != ESR_Succeeded)
3959 return ESR;
3960 }
3961 return ESR_Succeeded;
3962 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003963
3964 case Stmt::WhileStmtClass: {
3965 const WhileStmt *WS = cast<WhileStmt>(S);
3966 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003967 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003968 bool Continue;
3969 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3970 Continue))
3971 return ESR_Failed;
3972 if (!Continue)
3973 break;
3974
3975 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3976 if (ESR != ESR_Continue)
3977 return ESR;
3978 }
3979 return ESR_Succeeded;
3980 }
3981
3982 case Stmt::DoStmtClass: {
3983 const DoStmt *DS = cast<DoStmt>(S);
3984 bool Continue;
3985 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003986 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003987 if (ESR != ESR_Continue)
3988 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003989 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003990
Richard Smith08d6a2c2013-07-24 07:11:57 +00003991 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003992 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3993 return ESR_Failed;
3994 } while (Continue);
3995 return ESR_Succeeded;
3996 }
3997
3998 case Stmt::ForStmtClass: {
3999 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004000 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004001 if (FS->getInit()) {
4002 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4003 if (ESR != ESR_Succeeded)
4004 return ESR;
4005 }
4006 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004007 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004008 bool Continue = true;
4009 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4010 FS->getCond(), Continue))
4011 return ESR_Failed;
4012 if (!Continue)
4013 break;
4014
4015 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4016 if (ESR != ESR_Continue)
4017 return ESR;
4018
Richard Smith08d6a2c2013-07-24 07:11:57 +00004019 if (FS->getInc()) {
4020 FullExpressionRAII IncScope(Info);
4021 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4022 return ESR_Failed;
4023 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004024 }
4025 return ESR_Succeeded;
4026 }
4027
Richard Smith896e0d72013-05-06 06:51:17 +00004028 case Stmt::CXXForRangeStmtClass: {
4029 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004030 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004031
4032 // Initialize the __range variable.
4033 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4034 if (ESR != ESR_Succeeded)
4035 return ESR;
4036
4037 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004038 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4039 if (ESR != ESR_Succeeded)
4040 return ESR;
4041 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004042 if (ESR != ESR_Succeeded)
4043 return ESR;
4044
4045 while (true) {
4046 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004047 {
4048 bool Continue = true;
4049 FullExpressionRAII CondExpr(Info);
4050 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4051 return ESR_Failed;
4052 if (!Continue)
4053 break;
4054 }
Richard Smith896e0d72013-05-06 06:51:17 +00004055
4056 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004057 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004058 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4059 if (ESR != ESR_Succeeded)
4060 return ESR;
4061
4062 // Loop body.
4063 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4064 if (ESR != ESR_Continue)
4065 return ESR;
4066
4067 // Increment: ++__begin
4068 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4069 return ESR_Failed;
4070 }
4071
4072 return ESR_Succeeded;
4073 }
4074
Richard Smith496ddcf2013-05-12 17:32:42 +00004075 case Stmt::SwitchStmtClass:
4076 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4077
Richard Smith4e18ca52013-05-06 05:56:11 +00004078 case Stmt::ContinueStmtClass:
4079 return ESR_Continue;
4080
4081 case Stmt::BreakStmtClass:
4082 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004083
4084 case Stmt::LabelStmtClass:
4085 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4086
4087 case Stmt::AttributedStmtClass:
4088 // As a general principle, C++11 attributes can be ignored without
4089 // any semantic impact.
4090 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4091 Case);
4092
4093 case Stmt::CaseStmtClass:
4094 case Stmt::DefaultStmtClass:
4095 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004096 }
4097}
4098
Richard Smithcc36f692011-12-22 02:22:31 +00004099/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4100/// default constructor. If so, we'll fold it whether or not it's marked as
4101/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4102/// so we need special handling.
4103static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004104 const CXXConstructorDecl *CD,
4105 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004106 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4107 return false;
4108
Richard Smith66e05fe2012-01-18 05:21:49 +00004109 // Value-initialization does not call a trivial default constructor, so such a
4110 // call is a core constant expression whether or not the constructor is
4111 // constexpr.
4112 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004113 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004114 // FIXME: If DiagDecl is an implicitly-declared special member function,
4115 // we should be much more explicit about why it's not constexpr.
4116 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4117 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4118 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004119 } else {
4120 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4121 }
4122 }
4123 return true;
4124}
4125
Richard Smith357362d2011-12-13 06:39:58 +00004126/// CheckConstexprFunction - Check that a function can be called in a constant
4127/// expression.
4128static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4129 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004130 const FunctionDecl *Definition,
4131 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004132 // Potential constant expressions can contain calls to declared, but not yet
4133 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004134 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004135 Declaration->isConstexpr())
4136 return false;
4137
Richard Smith0838f3a2013-05-14 05:18:44 +00004138 // Bail out with no diagnostic if the function declaration itself is invalid.
4139 // We will have produced a relevant diagnostic while parsing it.
4140 if (Declaration->isInvalidDecl())
4141 return false;
4142
Richard Smith357362d2011-12-13 06:39:58 +00004143 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004144 if (Definition && Definition->isConstexpr() &&
4145 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004146 return true;
4147
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004148 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004149 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Daniel Jasperffdee092017-05-02 19:21:42 +00004150
Richard Smith5179eb72016-06-28 19:03:57 +00004151 // If this function is not constexpr because it is an inherited
4152 // non-constexpr constructor, diagnose that directly.
4153 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4154 if (CD && CD->isInheritingConstructor()) {
4155 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Daniel Jasperffdee092017-05-02 19:21:42 +00004156 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004157 DiagDecl = CD = Inherited;
4158 }
4159
4160 // FIXME: If DiagDecl is an implicitly-declared special member function
4161 // or an inheriting constructor, we should be much more explicit about why
4162 // it's not constexpr.
4163 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004164 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004165 << CD->getInheritedConstructor().getConstructor()->getParent();
4166 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004167 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004168 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004169 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4170 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004171 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004172 }
4173 return false;
4174}
4175
Richard Smithbe6dd812014-11-19 21:27:17 +00004176/// Determine if a class has any fields that might need to be copied by a
4177/// trivial copy or move operation.
4178static bool hasFields(const CXXRecordDecl *RD) {
4179 if (!RD || RD->isEmpty())
4180 return false;
4181 for (auto *FD : RD->fields()) {
4182 if (FD->isUnnamedBitfield())
4183 continue;
4184 return true;
4185 }
4186 for (auto &Base : RD->bases())
4187 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4188 return true;
4189 return false;
4190}
4191
Richard Smithd62306a2011-11-10 06:34:14 +00004192namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004193typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004194}
4195
4196/// EvaluateArgs - Evaluate the arguments to a function call.
4197static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4198 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004199 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004200 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004201 I != E; ++I) {
4202 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4203 // If we're checking for a potential constant expression, evaluate all
4204 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004205 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004206 return false;
4207 Success = false;
4208 }
4209 }
4210 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004211}
4212
Richard Smith254a73d2011-10-28 22:34:42 +00004213/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004214static bool HandleFunctionCall(SourceLocation CallLoc,
4215 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004216 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004217 EvalInfo &Info, APValue &Result,
4218 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004219 ArgVector ArgValues(Args.size());
4220 if (!EvaluateArgs(Args, ArgValues, Info))
4221 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004222
Richard Smith253c2a32012-01-27 01:14:48 +00004223 if (!Info.CheckCallLimit(CallLoc))
4224 return false;
4225
4226 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004227
4228 // For a trivial copy or move assignment, perform an APValue copy. This is
4229 // essential for unions, where the operations performed by the assignment
4230 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004231 //
4232 // Skip this for non-union classes with no fields; in that case, the defaulted
4233 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004234 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004235 if (MD && MD->isDefaulted() &&
4236 (MD->getParent()->isUnion() ||
4237 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004238 assert(This &&
4239 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4240 LValue RHS;
4241 RHS.setFrom(Info.Ctx, ArgValues[0]);
4242 APValue RHSValue;
4243 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4244 RHS, RHSValue))
4245 return false;
4246 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4247 RHSValue))
4248 return false;
4249 This->moveInto(Result);
4250 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004251 } else if (MD && isLambdaCallOperator(MD)) {
4252 // We're in a lambda; determine the lambda capture field maps.
4253 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4254 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004255 }
4256
Richard Smith52a980a2015-08-28 02:43:42 +00004257 StmtResult Ret = {Result, ResultSlot};
4258 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004259 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004260 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004261 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004262 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004263 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004264 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004265}
4266
Richard Smithd62306a2011-11-10 06:34:14 +00004267/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004268static bool HandleConstructorCall(const Expr *E, const LValue &This,
4269 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004270 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004271 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004272 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004273 if (!Info.CheckCallLimit(CallLoc))
4274 return false;
4275
Richard Smith3607ffe2012-02-13 03:54:03 +00004276 const CXXRecordDecl *RD = Definition->getParent();
4277 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004278 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004279 return false;
4280 }
4281
Erik Pilkington42925492017-10-04 00:18:55 +00004282 EvalInfo::EvaluatingConstructorRAII EvalObj(
4283 Info, {This.getLValueBase(), This.CallIndex});
Richard Smith5179eb72016-06-28 19:03:57 +00004284 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004285
Richard Smith52a980a2015-08-28 02:43:42 +00004286 // FIXME: Creating an APValue just to hold a nonexistent return value is
4287 // wasteful.
4288 APValue RetVal;
4289 StmtResult Ret = {RetVal, nullptr};
4290
Richard Smith5179eb72016-06-28 19:03:57 +00004291 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004292 if (Definition->isDelegatingConstructor()) {
4293 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004294 {
4295 FullExpressionRAII InitScope(Info);
4296 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4297 return false;
4298 }
Richard Smith52a980a2015-08-28 02:43:42 +00004299 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004300 }
4301
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004302 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004303 // essential for unions (or classes with anonymous union members), where the
4304 // operations performed by the constructor cannot be represented by
4305 // ctor-initializers.
4306 //
4307 // Skip this for empty non-union classes; we should not perform an
4308 // lvalue-to-rvalue conversion on them because their copy constructor does not
4309 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004310 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004311 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004312 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004313 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004314 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004315 return handleLValueToRValueConversion(
4316 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4317 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004318 }
4319
4320 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004321 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004322 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004323 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004324
John McCalld7bca762012-05-01 00:38:49 +00004325 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004326 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4327
Richard Smith08d6a2c2013-07-24 07:11:57 +00004328 // A scope for temporaries lifetime-extended by reference members.
4329 BlockScopeRAII LifetimeExtendedScope(Info);
4330
Richard Smith253c2a32012-01-27 01:14:48 +00004331 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004332 unsigned BasesSeen = 0;
4333#ifndef NDEBUG
4334 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4335#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004336 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004337 LValue Subobject = This;
4338 APValue *Value = &Result;
4339
4340 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004341 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004342 if (I->isBaseInitializer()) {
4343 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004344#ifndef NDEBUG
4345 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004346 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004347 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4348 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4349 "base class initializers not in expected order");
4350 ++BaseIt;
4351#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004352 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004353 BaseType->getAsCXXRecordDecl(), &Layout))
4354 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004355 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004356 } else if ((FD = I->getMember())) {
4357 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004358 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004359 if (RD->isUnion()) {
4360 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004361 Value = &Result.getUnionValue();
4362 } else {
4363 Value = &Result.getStructField(FD->getFieldIndex());
4364 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004365 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004366 // Walk the indirect field decl's chain to find the object to initialize,
4367 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004368 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004369 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004370 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4371 // Switch the union field if it differs. This happens if we had
4372 // preceding zero-initialization, and we're now initializing a union
4373 // subobject other than the first.
4374 // FIXME: In this case, the values of the other subobjects are
4375 // specified, since zero-initialization sets all padding bits to zero.
4376 if (Value->isUninit() ||
4377 (Value->isUnion() && Value->getUnionField() != FD)) {
4378 if (CD->isUnion())
4379 *Value = APValue(FD);
4380 else
4381 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004382 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004383 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004384 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004385 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004386 if (CD->isUnion())
4387 Value = &Value->getUnionValue();
4388 else
4389 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004390 }
Richard Smithd62306a2011-11-10 06:34:14 +00004391 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004392 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004393 }
Richard Smith253c2a32012-01-27 01:14:48 +00004394
Richard Smith08d6a2c2013-07-24 07:11:57 +00004395 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004396 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4397 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004398 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004399 // If we're checking for a potential constant expression, evaluate all
4400 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004401 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004402 return false;
4403 Success = false;
4404 }
Richard Smithd62306a2011-11-10 06:34:14 +00004405 }
4406
Richard Smithd9f663b2013-04-22 15:31:51 +00004407 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004408 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004409}
4410
Richard Smith5179eb72016-06-28 19:03:57 +00004411static bool HandleConstructorCall(const Expr *E, const LValue &This,
4412 ArrayRef<const Expr*> Args,
4413 const CXXConstructorDecl *Definition,
4414 EvalInfo &Info, APValue &Result) {
4415 ArgVector ArgValues(Args.size());
4416 if (!EvaluateArgs(Args, ArgValues, Info))
4417 return false;
4418
4419 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4420 Info, Result);
4421}
4422
Eli Friedman9a156e52008-11-12 09:44:48 +00004423//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004424// Generic Evaluation
4425//===----------------------------------------------------------------------===//
4426namespace {
4427
Aaron Ballman68af21c2014-01-03 19:26:43 +00004428template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004429class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004430 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004431private:
Richard Smith52a980a2015-08-28 02:43:42 +00004432 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004433 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004434 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004435 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004436 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004437 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004438 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004439
Richard Smith17100ba2012-02-16 02:46:34 +00004440 // Check whether a conditional operator with a non-constant condition is a
4441 // potential constant expression. If neither arm is a potential constant
4442 // expression, then the conditional operator is not either.
4443 template<typename ConditionalOperator>
4444 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004445 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004446
4447 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004448 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004449 {
Richard Smith17100ba2012-02-16 02:46:34 +00004450 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004451 StmtVisitorTy::Visit(E->getFalseExpr());
4452 if (Diag.empty())
4453 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004454 }
Richard Smith17100ba2012-02-16 02:46:34 +00004455
George Burgess IV8c892b52016-05-25 22:31:54 +00004456 {
4457 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004458 Diag.clear();
4459 StmtVisitorTy::Visit(E->getTrueExpr());
4460 if (Diag.empty())
4461 return;
4462 }
4463
4464 Error(E, diag::note_constexpr_conditional_never_const);
4465 }
4466
4467
4468 template<typename ConditionalOperator>
4469 bool HandleConditionalOperator(const ConditionalOperator *E) {
4470 bool BoolResult;
4471 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004472 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004473 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004474 return false;
4475 }
4476 if (Info.noteFailure()) {
4477 StmtVisitorTy::Visit(E->getTrueExpr());
4478 StmtVisitorTy::Visit(E->getFalseExpr());
4479 }
Richard Smith17100ba2012-02-16 02:46:34 +00004480 return false;
4481 }
4482
4483 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4484 return StmtVisitorTy::Visit(EvalExpr);
4485 }
4486
Peter Collingbournee9200682011-05-13 03:29:01 +00004487protected:
4488 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004489 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004490 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4491
Richard Smith92b1ce02011-12-12 09:28:41 +00004492 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004493 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004494 }
4495
Aaron Ballman68af21c2014-01-03 19:26:43 +00004496 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004497
4498public:
4499 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4500
4501 EvalInfo &getEvalInfo() { return Info; }
4502
Richard Smithf57d8cb2011-12-09 22:58:01 +00004503 /// Report an evaluation error. This should only be called when an error is
4504 /// first discovered. When propagating an error, just return false.
4505 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004506 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004507 return false;
4508 }
4509 bool Error(const Expr *E) {
4510 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4511 }
4512
Aaron Ballman68af21c2014-01-03 19:26:43 +00004513 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004514 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004515 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004516 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004517 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004518 }
4519
Aaron Ballman68af21c2014-01-03 19:26:43 +00004520 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004521 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004522 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004523 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004524 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004525 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004526 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004527 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004528 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004529 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004530 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004531 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004532 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004533 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004534 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004535 // The initializer may not have been parsed yet, or might be erroneous.
4536 if (!E->getExpr())
4537 return Error(E);
4538 return StmtVisitorTy::Visit(E->getExpr());
4539 }
Richard Smith5894a912011-12-19 22:12:41 +00004540 // We cannot create any objects for which cleanups are required, so there is
4541 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004542 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004543 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004544
Aaron Ballman68af21c2014-01-03 19:26:43 +00004545 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004546 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4547 return static_cast<Derived*>(this)->VisitCastExpr(E);
4548 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004549 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004550 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4551 return static_cast<Derived*>(this)->VisitCastExpr(E);
4552 }
4553
Aaron Ballman68af21c2014-01-03 19:26:43 +00004554 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004555 switch (E->getOpcode()) {
4556 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004557 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004558
4559 case BO_Comma:
4560 VisitIgnoredValue(E->getLHS());
4561 return StmtVisitorTy::Visit(E->getRHS());
4562
4563 case BO_PtrMemD:
4564 case BO_PtrMemI: {
4565 LValue Obj;
4566 if (!HandleMemberPointerAccess(Info, E, Obj))
4567 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004568 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004569 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004570 return false;
4571 return DerivedSuccess(Result, E);
4572 }
4573 }
4574 }
4575
Aaron Ballman68af21c2014-01-03 19:26:43 +00004576 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004577 // Evaluate and cache the common expression. We treat it as a temporary,
4578 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004579 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004580 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004581 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004582
Richard Smith17100ba2012-02-16 02:46:34 +00004583 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004584 }
4585
Aaron Ballman68af21c2014-01-03 19:26:43 +00004586 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004587 bool IsBcpCall = false;
4588 // If the condition (ignoring parens) is a __builtin_constant_p call,
4589 // the result is a constant expression if it can be folded without
4590 // side-effects. This is an important GNU extension. See GCC PR38377
4591 // for discussion.
4592 if (const CallExpr *CallCE =
4593 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004594 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004595 IsBcpCall = true;
4596
4597 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4598 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004599 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004600 return false;
4601
Richard Smith6d4c6582013-11-05 22:18:15 +00004602 FoldConstant Fold(Info, IsBcpCall);
4603 if (!HandleConditionalOperator(E)) {
4604 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004605 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004606 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004607
4608 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004609 }
4610
Aaron Ballman68af21c2014-01-03 19:26:43 +00004611 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004612 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4613 return DerivedSuccess(*Value, E);
4614
4615 const Expr *Source = E->getSourceExpr();
4616 if (!Source)
4617 return Error(E);
4618 if (Source == E) { // sanity checking.
4619 assert(0 && "OpaqueValueExpr recursively refers to itself");
4620 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004621 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004622 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004623 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004624
Aaron Ballman68af21c2014-01-03 19:26:43 +00004625 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004626 APValue Result;
4627 if (!handleCallExpr(E, Result, nullptr))
4628 return false;
4629 return DerivedSuccess(Result, E);
4630 }
4631
4632 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004633 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004634 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004635 QualType CalleeType = Callee->getType();
4636
Craig Topper36250ad2014-05-12 05:36:57 +00004637 const FunctionDecl *FD = nullptr;
4638 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004639 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004640 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004641
Richard Smithe97cbd72011-11-11 04:05:33 +00004642 // Extract function decl and 'this' pointer from the callee.
4643 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004644 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004645 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4646 // Explicit bound member calls, such as x.f() or p->g();
4647 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004648 return false;
4649 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004650 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004651 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004652 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4653 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004654 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4655 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004656 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004657 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004658 return Error(Callee);
4659
4660 FD = dyn_cast<FunctionDecl>(Member);
4661 if (!FD)
4662 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004663 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004664 LValue Call;
4665 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004666 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004667
Richard Smitha8105bc2012-01-06 16:39:00 +00004668 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004669 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004670 FD = dyn_cast_or_null<FunctionDecl>(
4671 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004672 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004673 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004674 // Don't call function pointers which have been cast to some other type.
4675 // Per DR (no number yet), the caller and callee can differ in noexcept.
4676 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4677 CalleeType->getPointeeType(), FD->getType())) {
4678 return Error(E);
4679 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004680
4681 // Overloaded operator calls to member functions are represented as normal
4682 // calls with '*this' as the first argument.
4683 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4684 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004685 // FIXME: When selecting an implicit conversion for an overloaded
4686 // operator delete, we sometimes try to evaluate calls to conversion
4687 // operators without a 'this' parameter!
4688 if (Args.empty())
4689 return Error(E);
4690
Nick Lewycky13073a62017-06-12 21:15:44 +00004691 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004692 return false;
4693 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004694 Args = Args.slice(1);
Daniel Jasperffdee092017-05-02 19:21:42 +00004695 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004696 // Map the static invoker for the lambda back to the call operator.
4697 // Conveniently, we don't have to slice out the 'this' argument (as is
4698 // being done for the non-static case), since a static member function
4699 // doesn't have an implicit argument passed in.
4700 const CXXRecordDecl *ClosureClass = MD->getParent();
4701 assert(
4702 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4703 "Number of captures must be zero for conversion to function-ptr");
4704
4705 const CXXMethodDecl *LambdaCallOp =
4706 ClosureClass->getLambdaCallOperator();
4707
4708 // Set 'FD', the function that will be called below, to the call
4709 // operator. If the closure object represents a generic lambda, find
4710 // the corresponding specialization of the call operator.
4711
4712 if (ClosureClass->isGenericLambda()) {
4713 assert(MD->isFunctionTemplateSpecialization() &&
4714 "A generic lambda's static-invoker function must be a "
4715 "template specialization");
4716 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4717 FunctionTemplateDecl *CallOpTemplate =
4718 LambdaCallOp->getDescribedFunctionTemplate();
4719 void *InsertPos = nullptr;
4720 FunctionDecl *CorrespondingCallOpSpecialization =
4721 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4722 assert(CorrespondingCallOpSpecialization &&
4723 "We must always have a function call operator specialization "
4724 "that corresponds to our static invoker specialization");
4725 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4726 } else
4727 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004728 }
4729
Daniel Jasperffdee092017-05-02 19:21:42 +00004730
Richard Smithe97cbd72011-11-11 04:05:33 +00004731 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004732 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004733
Richard Smith47b34932012-02-01 02:39:43 +00004734 if (This && !This->checkSubobject(Info, E, CSK_This))
4735 return false;
4736
Richard Smith3607ffe2012-02-13 03:54:03 +00004737 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4738 // calls to such functions in constant expressions.
4739 if (This && !HasQualifier &&
4740 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4741 return Error(E, diag::note_constexpr_virtual_call);
4742
Craig Topper36250ad2014-05-12 05:36:57 +00004743 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004744 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004745
Nick Lewycky13073a62017-06-12 21:15:44 +00004746 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4747 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004748 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004749 return false;
4750
Richard Smith52a980a2015-08-28 02:43:42 +00004751 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004752 }
4753
Aaron Ballman68af21c2014-01-03 19:26:43 +00004754 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004755 return StmtVisitorTy::Visit(E->getInitializer());
4756 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004757 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004758 if (E->getNumInits() == 0)
4759 return DerivedZeroInitialization(E);
4760 if (E->getNumInits() == 1)
4761 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004762 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004763 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004764 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004765 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004766 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004767 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004768 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004769 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004770 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004771 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004772 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004773
Richard Smithd62306a2011-11-10 06:34:14 +00004774 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004775 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004776 assert(!E->isArrow() && "missing call to bound member function?");
4777
Richard Smith2e312c82012-03-03 22:46:17 +00004778 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004779 if (!Evaluate(Val, Info, E->getBase()))
4780 return false;
4781
4782 QualType BaseTy = E->getBase()->getType();
4783
4784 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004785 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004786 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004787 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004788 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4789
Richard Smith3229b742013-05-05 21:17:10 +00004790 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004791 SubobjectDesignator Designator(BaseTy);
4792 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004793
Richard Smith3229b742013-05-05 21:17:10 +00004794 APValue Result;
4795 return extractSubobject(Info, E, Obj, Designator, Result) &&
4796 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004797 }
4798
Aaron Ballman68af21c2014-01-03 19:26:43 +00004799 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004800 switch (E->getCastKind()) {
4801 default:
4802 break;
4803
Richard Smitha23ab512013-05-23 00:30:41 +00004804 case CK_AtomicToNonAtomic: {
4805 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004806 // This does not need to be done in place even for class/array types:
4807 // atomic-to-non-atomic conversion implies copying the object
4808 // representation.
4809 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004810 return false;
4811 return DerivedSuccess(AtomicVal, E);
4812 }
4813
Richard Smith11562c52011-10-28 17:51:58 +00004814 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004815 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004816 return StmtVisitorTy::Visit(E->getSubExpr());
4817
4818 case CK_LValueToRValue: {
4819 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004820 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4821 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004822 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004823 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004824 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004825 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004826 return false;
4827 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004828 }
4829 }
4830
Richard Smithf57d8cb2011-12-09 22:58:01 +00004831 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004832 }
4833
Aaron Ballman68af21c2014-01-03 19:26:43 +00004834 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004835 return VisitUnaryPostIncDec(UO);
4836 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004837 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004838 return VisitUnaryPostIncDec(UO);
4839 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004840 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004841 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004842 return Error(UO);
4843
4844 LValue LVal;
4845 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4846 return false;
4847 APValue RVal;
4848 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4849 UO->isIncrementOp(), &RVal))
4850 return false;
4851 return DerivedSuccess(RVal, UO);
4852 }
4853
Aaron Ballman68af21c2014-01-03 19:26:43 +00004854 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004855 // We will have checked the full-expressions inside the statement expression
4856 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004857 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004858 return Error(E);
4859
Richard Smith08d6a2c2013-07-24 07:11:57 +00004860 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004861 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004862 if (CS->body_empty())
4863 return true;
4864
Richard Smith51f03172013-06-20 03:00:05 +00004865 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4866 BE = CS->body_end();
4867 /**/; ++BI) {
4868 if (BI + 1 == BE) {
4869 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4870 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004871 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004872 diag::note_constexpr_stmt_expr_unsupported);
4873 return false;
4874 }
4875 return this->Visit(FinalExpr);
4876 }
4877
4878 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004879 StmtResult Result = { ReturnValue, nullptr };
4880 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004881 if (ESR != ESR_Succeeded) {
4882 // FIXME: If the statement-expression terminated due to 'return',
4883 // 'break', or 'continue', it would be nice to propagate that to
4884 // the outer statement evaluation rather than bailing out.
4885 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004886 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004887 diag::note_constexpr_stmt_expr_unsupported);
4888 return false;
4889 }
4890 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004891
4892 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004893 }
4894
Richard Smith4a678122011-10-24 18:44:57 +00004895 /// Visit a value which is evaluated, but whose value is ignored.
4896 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004897 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004898 }
David Majnemere9807b22016-02-26 04:23:19 +00004899
4900 /// Potentially visit a MemberExpr's base expression.
4901 void VisitIgnoredBaseExpression(const Expr *E) {
4902 // While MSVC doesn't evaluate the base expression, it does diagnose the
4903 // presence of side-effecting behavior.
4904 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4905 return;
4906 VisitIgnoredValue(E);
4907 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004908};
4909
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004910}
Peter Collingbournee9200682011-05-13 03:29:01 +00004911
4912//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004913// Common base class for lvalue and temporary evaluation.
4914//===----------------------------------------------------------------------===//
4915namespace {
4916template<class Derived>
4917class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004918 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004919protected:
4920 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00004921 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00004922 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004923 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004924
4925 bool Success(APValue::LValueBase B) {
4926 Result.set(B);
4927 return true;
4928 }
4929
George Burgess IVf9013bf2017-02-10 22:52:29 +00004930 bool evaluatePointer(const Expr *E, LValue &Result) {
4931 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4932 }
4933
Richard Smith027bf112011-11-17 22:56:20 +00004934public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004935 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4936 : ExprEvaluatorBaseTy(Info), Result(Result),
4937 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00004938
Richard Smith2e312c82012-03-03 22:46:17 +00004939 bool Success(const APValue &V, const Expr *E) {
4940 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004941 return true;
4942 }
Richard Smith027bf112011-11-17 22:56:20 +00004943
Richard Smith027bf112011-11-17 22:56:20 +00004944 bool VisitMemberExpr(const MemberExpr *E) {
4945 // Handle non-static data members.
4946 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004947 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004948 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004949 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00004950 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004951 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004952 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004953 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004954 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004955 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004956 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004957 BaseTy = E->getBase()->getType();
4958 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004959 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004960 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004961 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004962 Result.setInvalid(E);
4963 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004964 }
Richard Smith027bf112011-11-17 22:56:20 +00004965
Richard Smith1b78b3d2012-01-25 22:15:11 +00004966 const ValueDecl *MD = E->getMemberDecl();
4967 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4968 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4969 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4970 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004971 if (!HandleLValueMember(this->Info, E, Result, FD))
4972 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004973 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004974 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4975 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004976 } else
4977 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004978
Richard Smith1b78b3d2012-01-25 22:15:11 +00004979 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004980 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004981 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004982 RefValue))
4983 return false;
4984 return Success(RefValue, E);
4985 }
4986 return true;
4987 }
4988
4989 bool VisitBinaryOperator(const BinaryOperator *E) {
4990 switch (E->getOpcode()) {
4991 default:
4992 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4993
4994 case BO_PtrMemD:
4995 case BO_PtrMemI:
4996 return HandleMemberPointerAccess(this->Info, E, Result);
4997 }
4998 }
4999
5000 bool VisitCastExpr(const CastExpr *E) {
5001 switch (E->getCastKind()) {
5002 default:
5003 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5004
5005 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005006 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005007 if (!this->Visit(E->getSubExpr()))
5008 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005009
5010 // Now figure out the necessary offset to add to the base LV to get from
5011 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005012 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5013 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005014 }
5015 }
5016};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005017}
Richard Smith027bf112011-11-17 22:56:20 +00005018
5019//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005020// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005021//
5022// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5023// function designators (in C), decl references to void objects (in C), and
5024// temporaries (if building with -Wno-address-of-temporary).
5025//
5026// LValue evaluation produces values comprising a base expression of one of the
5027// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005028// - Declarations
5029// * VarDecl
5030// * FunctionDecl
5031// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005032// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005033// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005034// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005035// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005036// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005037// * ObjCEncodeExpr
5038// * AddrLabelExpr
5039// * BlockExpr
5040// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005041// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005042// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005043// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005044// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5045// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005046// * A MaterializeTemporaryExpr that has static storage duration, with no
5047// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005048// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005049//===----------------------------------------------------------------------===//
5050namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005051class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005052 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005053public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005054 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5055 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005056
Richard Smith11562c52011-10-28 17:51:58 +00005057 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005058 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005059
Peter Collingbournee9200682011-05-13 03:29:01 +00005060 bool VisitDeclRefExpr(const DeclRefExpr *E);
5061 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005062 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005063 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5064 bool VisitMemberExpr(const MemberExpr *E);
5065 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5066 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005067 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005068 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005069 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5070 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005071 bool VisitUnaryReal(const UnaryOperator *E);
5072 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005073 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5074 return VisitUnaryPreIncDec(UO);
5075 }
5076 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5077 return VisitUnaryPreIncDec(UO);
5078 }
Richard Smith3229b742013-05-05 21:17:10 +00005079 bool VisitBinAssign(const BinaryOperator *BO);
5080 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005081
Peter Collingbournee9200682011-05-13 03:29:01 +00005082 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005083 switch (E->getCastKind()) {
5084 default:
Richard Smith027bf112011-11-17 22:56:20 +00005085 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005086
Eli Friedmance3e02a2011-10-11 00:13:24 +00005087 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005088 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005089 if (!Visit(E->getSubExpr()))
5090 return false;
5091 Result.Designator.setInvalid();
5092 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005093
Richard Smith027bf112011-11-17 22:56:20 +00005094 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005095 if (!Visit(E->getSubExpr()))
5096 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005097 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005098 }
5099 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005100};
5101} // end anonymous namespace
5102
Richard Smith11562c52011-10-28 17:51:58 +00005103/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005104/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005105/// * function designators in C, and
5106/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005107/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005108static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5109 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005110 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005111 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005112 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005113}
5114
Peter Collingbournee9200682011-05-13 03:29:01 +00005115bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005116 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005117 return Success(FD);
5118 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005119 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005120 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005121 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005122 return Error(E);
5123}
Richard Smith733237d2011-10-24 23:14:33 +00005124
Faisal Vali0528a312016-11-13 06:09:16 +00005125
Richard Smith11562c52011-10-28 17:51:58 +00005126bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005127
5128 // If we are within a lambda's call operator, check whether the 'VD' referred
5129 // to within 'E' actually represents a lambda-capture that maps to a
5130 // data-member/field within the closure object, and if so, evaluate to the
5131 // field or what the field refers to.
5132 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5133 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5134 if (Info.checkingPotentialConstantExpression())
5135 return false;
5136 // Start with 'Result' referring to the complete closure object...
5137 Result = *Info.CurrentCall->This;
5138 // ... then update it to refer to the field of the closure object
5139 // that represents the capture.
5140 if (!HandleLValueMember(Info, E, Result, FD))
5141 return false;
5142 // And if the field is of reference type, update 'Result' to refer to what
5143 // the field refers to.
5144 if (FD->getType()->isReferenceType()) {
5145 APValue RVal;
5146 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5147 RVal))
5148 return false;
5149 Result.setFrom(Info.Ctx, RVal);
5150 }
5151 return true;
5152 }
5153 }
Craig Topper36250ad2014-05-12 05:36:57 +00005154 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005155 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5156 // Only if a local variable was declared in the function currently being
5157 // evaluated, do we expect to be able to find its value in the current
5158 // frame. (Otherwise it was likely declared in an enclosing context and
5159 // could either have a valid evaluatable value (for e.g. a constexpr
5160 // variable) or be ill-formed (and trigger an appropriate evaluation
5161 // diagnostic)).
5162 if (Info.CurrentCall->Callee &&
5163 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5164 Frame = Info.CurrentCall;
5165 }
5166 }
Richard Smith3229b742013-05-05 21:17:10 +00005167
Richard Smithfec09922011-11-01 16:57:24 +00005168 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005169 if (Frame) {
5170 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005171 return true;
5172 }
Richard Smithce40ad62011-11-12 22:28:03 +00005173 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005174 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005175
Richard Smith3229b742013-05-05 21:17:10 +00005176 APValue *V;
5177 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005178 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005179 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005180 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005181 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005182 return false;
5183 }
Richard Smith3229b742013-05-05 21:17:10 +00005184 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005185}
5186
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005187bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5188 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005189 // Walk through the expression to find the materialized temporary itself.
5190 SmallVector<const Expr *, 2> CommaLHSs;
5191 SmallVector<SubobjectAdjustment, 2> Adjustments;
5192 const Expr *Inner = E->GetTemporaryExpr()->
5193 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005194
Richard Smith84401042013-06-03 05:03:02 +00005195 // If we passed any comma operators, evaluate their LHSs.
5196 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5197 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5198 return false;
5199
Richard Smithe6c01442013-06-05 00:46:14 +00005200 // A materialized temporary with static storage duration can appear within the
5201 // result of a constant expression evaluation, so we need to preserve its
5202 // value for use outside this evaluation.
5203 APValue *Value;
5204 if (E->getStorageDuration() == SD_Static) {
5205 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005206 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005207 Result.set(E);
5208 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005209 Value = &Info.CurrentCall->
5210 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005211 Result.set(E, Info.CurrentCall->Index);
5212 }
5213
Richard Smithea4ad5d2013-06-06 08:19:16 +00005214 QualType Type = Inner->getType();
5215
Richard Smith84401042013-06-03 05:03:02 +00005216 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005217 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5218 (E->getStorageDuration() == SD_Static &&
5219 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5220 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005221 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005222 }
Richard Smith84401042013-06-03 05:03:02 +00005223
5224 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005225 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5226 --I;
5227 switch (Adjustments[I].Kind) {
5228 case SubobjectAdjustment::DerivedToBaseAdjustment:
5229 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5230 Type, Result))
5231 return false;
5232 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5233 break;
5234
5235 case SubobjectAdjustment::FieldAdjustment:
5236 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5237 return false;
5238 Type = Adjustments[I].Field->getType();
5239 break;
5240
5241 case SubobjectAdjustment::MemberPointerAdjustment:
5242 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5243 Adjustments[I].Ptr.RHS))
5244 return false;
5245 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5246 break;
5247 }
5248 }
5249
5250 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005251}
5252
Peter Collingbournee9200682011-05-13 03:29:01 +00005253bool
5254LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005255 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5256 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005257 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5258 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005259 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005260}
5261
Richard Smith6e525142011-12-27 12:18:28 +00005262bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005263 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005264 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005265
Faisal Valie690b7a2016-07-02 22:34:24 +00005266 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005267 << E->getExprOperand()->getType()
5268 << E->getExprOperand()->getSourceRange();
5269 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005270}
5271
Francois Pichet0066db92012-04-16 04:08:35 +00005272bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5273 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005274}
Francois Pichet0066db92012-04-16 04:08:35 +00005275
Peter Collingbournee9200682011-05-13 03:29:01 +00005276bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005277 // Handle static data members.
5278 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005279 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005280 return VisitVarDecl(E, VD);
5281 }
5282
Richard Smith254a73d2011-10-28 22:34:42 +00005283 // Handle static member functions.
5284 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5285 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005286 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005287 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005288 }
5289 }
5290
Richard Smithd62306a2011-11-10 06:34:14 +00005291 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005292 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005293}
5294
Peter Collingbournee9200682011-05-13 03:29:01 +00005295bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005296 // FIXME: Deal with vectors as array subscript bases.
5297 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005298 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005299
Nick Lewyckyad888682017-04-27 07:27:36 +00005300 bool Success = true;
5301 if (!evaluatePointer(E->getBase(), Result)) {
5302 if (!Info.noteFailure())
5303 return false;
5304 Success = false;
5305 }
Mike Stump11289f42009-09-09 15:08:12 +00005306
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005307 APSInt Index;
5308 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005309 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005310
Nick Lewyckyad888682017-04-27 07:27:36 +00005311 return Success &&
5312 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005313}
Eli Friedman9a156e52008-11-12 09:44:48 +00005314
Peter Collingbournee9200682011-05-13 03:29:01 +00005315bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005316 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005317}
5318
Richard Smith66c96992012-02-18 22:04:06 +00005319bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5320 if (!Visit(E->getSubExpr()))
5321 return false;
5322 // __real is a no-op on scalar lvalues.
5323 if (E->getSubExpr()->getType()->isAnyComplexType())
5324 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5325 return true;
5326}
5327
5328bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5329 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5330 "lvalue __imag__ on scalar?");
5331 if (!Visit(E->getSubExpr()))
5332 return false;
5333 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5334 return true;
5335}
5336
Richard Smith243ef902013-05-05 23:31:59 +00005337bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005338 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005339 return Error(UO);
5340
5341 if (!this->Visit(UO->getSubExpr()))
5342 return false;
5343
Richard Smith243ef902013-05-05 23:31:59 +00005344 return handleIncDec(
5345 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005346 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005347}
5348
5349bool LValueExprEvaluator::VisitCompoundAssignOperator(
5350 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005351 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005352 return Error(CAO);
5353
Richard Smith3229b742013-05-05 21:17:10 +00005354 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005355
5356 // The overall lvalue result is the result of evaluating the LHS.
5357 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005358 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005359 Evaluate(RHS, this->Info, CAO->getRHS());
5360 return false;
5361 }
5362
Richard Smith3229b742013-05-05 21:17:10 +00005363 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5364 return false;
5365
Richard Smith43e77732013-05-07 04:50:00 +00005366 return handleCompoundAssignment(
5367 this->Info, CAO,
5368 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5369 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005370}
5371
5372bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005373 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005374 return Error(E);
5375
Richard Smith3229b742013-05-05 21:17:10 +00005376 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005377
5378 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005379 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005380 Evaluate(NewVal, this->Info, E->getRHS());
5381 return false;
5382 }
5383
Richard Smith3229b742013-05-05 21:17:10 +00005384 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5385 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005386
5387 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005388 NewVal);
5389}
5390
Eli Friedman9a156e52008-11-12 09:44:48 +00005391//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005392// Pointer Evaluation
5393//===----------------------------------------------------------------------===//
5394
George Burgess IVe3763372016-12-22 02:50:20 +00005395/// \brief Attempts to compute the number of bytes available at the pointer
5396/// returned by a function with the alloc_size attribute. Returns true if we
5397/// were successful. Places an unsigned number into `Result`.
5398///
5399/// This expects the given CallExpr to be a call to a function with an
5400/// alloc_size attribute.
5401static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5402 const CallExpr *Call,
5403 llvm::APInt &Result) {
5404 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5405
5406 // alloc_size args are 1-indexed, 0 means not present.
5407 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5408 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5409 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5410 if (Call->getNumArgs() <= SizeArgNo)
5411 return false;
5412
5413 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5414 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5415 return false;
5416 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5417 return false;
5418 Into = Into.zextOrSelf(BitsInSizeT);
5419 return true;
5420 };
5421
5422 APSInt SizeOfElem;
5423 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5424 return false;
5425
5426 if (!AllocSize->getNumElemsParam()) {
5427 Result = std::move(SizeOfElem);
5428 return true;
5429 }
5430
5431 APSInt NumberOfElems;
5432 // Argument numbers start at 1
5433 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5434 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5435 return false;
5436
5437 bool Overflow;
5438 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5439 if (Overflow)
5440 return false;
5441
5442 Result = std::move(BytesAvailable);
5443 return true;
5444}
5445
5446/// \brief Convenience function. LVal's base must be a call to an alloc_size
5447/// function.
5448static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5449 const LValue &LVal,
5450 llvm::APInt &Result) {
5451 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5452 "Can't get the size of a non alloc_size function");
5453 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5454 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5455 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5456}
5457
5458/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5459/// a function with the alloc_size attribute. If it was possible to do so, this
5460/// function will return true, make Result's Base point to said function call,
5461/// and mark Result's Base as invalid.
5462static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5463 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005464 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005465 return false;
5466
5467 // Because we do no form of static analysis, we only support const variables.
5468 //
5469 // Additionally, we can't support parameters, nor can we support static
5470 // variables (in the latter case, use-before-assign isn't UB; in the former,
5471 // we have no clue what they'll be assigned to).
5472 const auto *VD =
5473 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5474 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5475 return false;
5476
5477 const Expr *Init = VD->getAnyInitializer();
5478 if (!Init)
5479 return false;
5480
5481 const Expr *E = Init->IgnoreParens();
5482 if (!tryUnwrapAllocSizeCall(E))
5483 return false;
5484
5485 // Store E instead of E unwrapped so that the type of the LValue's base is
5486 // what the user wanted.
5487 Result.setInvalid(E);
5488
5489 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Martin Bohme542c84b2017-08-30 10:44:46 +00005490 Result.addUnsizedArray(Info, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005491 return true;
5492}
5493
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005494namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005495class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005496 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005497 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005498 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005499
Peter Collingbournee9200682011-05-13 03:29:01 +00005500 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005501 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005502 return true;
5503 }
George Burgess IVe3763372016-12-22 02:50:20 +00005504
George Burgess IVf9013bf2017-02-10 22:52:29 +00005505 bool evaluateLValue(const Expr *E, LValue &Result) {
5506 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5507 }
5508
5509 bool evaluatePointer(const Expr *E, LValue &Result) {
5510 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5511 }
5512
George Burgess IVe3763372016-12-22 02:50:20 +00005513 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005514public:
Mike Stump11289f42009-09-09 15:08:12 +00005515
George Burgess IVf9013bf2017-02-10 22:52:29 +00005516 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5517 : ExprEvaluatorBaseTy(info), Result(Result),
5518 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005519
Richard Smith2e312c82012-03-03 22:46:17 +00005520 bool Success(const APValue &V, const Expr *E) {
5521 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005522 return true;
5523 }
Richard Smithfddd3842011-12-30 21:15:51 +00005524 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005525 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5526 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005527 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005528 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005529
John McCall45d55e42010-05-07 21:00:08 +00005530 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005531 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005532 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005533 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005534 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005535 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5536 if (Info.noteFailure())
5537 EvaluateIgnoredValue(Info, E->getSubExpr());
5538 return Error(E);
5539 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005540 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005541 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005542 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005543 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005544 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005545 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005546 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005547 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005548 }
Richard Smithd62306a2011-11-10 06:34:14 +00005549 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005550 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005551 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005552 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005553 if (!Info.CurrentCall->This) {
5554 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005555 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005556 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005557 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005558 return false;
5559 }
Richard Smithd62306a2011-11-10 06:34:14 +00005560 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005561 // If we are inside a lambda's call operator, the 'this' expression refers
5562 // to the enclosing '*this' object (either by value or reference) which is
5563 // either copied into the closure object's field that represents the '*this'
5564 // or refers to '*this'.
5565 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5566 // Update 'Result' to refer to the data member/field of the closure object
5567 // that represents the '*this' capture.
5568 if (!HandleLValueMember(Info, E, Result,
Daniel Jasperffdee092017-05-02 19:21:42 +00005569 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005570 return false;
5571 // If we captured '*this' by reference, replace the field with its referent.
5572 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5573 ->isPointerType()) {
5574 APValue RVal;
5575 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5576 RVal))
5577 return false;
5578
5579 Result.setFrom(Info.Ctx, RVal);
5580 }
5581 }
Richard Smithd62306a2011-11-10 06:34:14 +00005582 return true;
5583 }
John McCallc07a0c72011-02-17 10:25:35 +00005584
Eli Friedman449fe542009-03-23 04:56:01 +00005585 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005586};
Chris Lattner05706e882008-07-11 18:11:29 +00005587} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005588
George Burgess IVf9013bf2017-02-10 22:52:29 +00005589static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5590 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005591 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005592 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005593}
5594
John McCall45d55e42010-05-07 21:00:08 +00005595bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005596 if (E->getOpcode() != BO_Add &&
5597 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005598 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005599
Chris Lattner05706e882008-07-11 18:11:29 +00005600 const Expr *PExp = E->getLHS();
5601 const Expr *IExp = E->getRHS();
5602 if (IExp->getType()->isPointerType())
5603 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005604
George Burgess IVf9013bf2017-02-10 22:52:29 +00005605 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005606 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005607 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005608
John McCall45d55e42010-05-07 21:00:08 +00005609 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005610 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005611 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005612
Richard Smith96e0c102011-11-04 02:25:55 +00005613 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005614 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005615
Ted Kremenek28831752012-08-23 20:46:57 +00005616 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005617 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005618}
Eli Friedman9a156e52008-11-12 09:44:48 +00005619
John McCall45d55e42010-05-07 21:00:08 +00005620bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005621 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005622}
Mike Stump11289f42009-09-09 15:08:12 +00005623
Peter Collingbournee9200682011-05-13 03:29:01 +00005624bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5625 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005626
Eli Friedman847a2bc2009-12-27 05:43:15 +00005627 switch (E->getCastKind()) {
5628 default:
5629 break;
5630
John McCalle3027922010-08-25 11:45:40 +00005631 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005632 case CK_CPointerToObjCPointerCast:
5633 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005634 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005635 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005636 if (!Visit(SubExpr))
5637 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005638 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5639 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5640 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005641 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005642 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005643 if (SubExpr->getType()->isVoidPointerType())
5644 CCEDiag(E, diag::note_constexpr_invalid_cast)
5645 << 3 << SubExpr->getType();
5646 else
5647 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5648 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005649 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5650 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005651 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005652
Anders Carlsson18275092010-10-31 20:41:46 +00005653 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005654 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005655 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005656 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005657 if (!Result.Base && Result.Offset.isZero())
5658 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005659
Richard Smithd62306a2011-11-10 06:34:14 +00005660 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005661 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005662 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5663 castAs<PointerType>()->getPointeeType(),
5664 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005665
Richard Smith027bf112011-11-17 22:56:20 +00005666 case CK_BaseToDerived:
5667 if (!Visit(E->getSubExpr()))
5668 return false;
5669 if (!Result.Base && Result.Offset.isZero())
5670 return true;
5671 return HandleBaseToDerivedCast(Info, E, Result);
5672
Richard Smith0b0a0b62011-10-29 20:57:55 +00005673 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005674 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005675 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005676
John McCalle3027922010-08-25 11:45:40 +00005677 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005678 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5679
Richard Smith2e312c82012-03-03 22:46:17 +00005680 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005681 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005682 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005683
John McCall45d55e42010-05-07 21:00:08 +00005684 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005685 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5686 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005687 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005688 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005689 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005690 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005691 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005692 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005693 return true;
5694 } else {
5695 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005696 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005697 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005698 }
5699 }
Martin Bohme542c84b2017-08-30 10:44:46 +00005700 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005701 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005702 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005703 return false;
5704 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005705 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005706 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005707 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005708 return false;
5709 }
Richard Smith96e0c102011-11-04 02:25:55 +00005710 // The result is a pointer to the first element of the array.
Martin Bohme542c84b2017-08-30 10:44:46 +00005711 if (const ConstantArrayType *CAT
5712 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
Richard Smitha8105bc2012-01-06 16:39:00 +00005713 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005714 else
Martin Bohme542c84b2017-08-30 10:44:46 +00005715 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005716 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005717
John McCalle3027922010-08-25 11:45:40 +00005718 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005719 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005720
5721 case CK_LValueToRValue: {
5722 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005723 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005724 return false;
5725
5726 APValue RVal;
5727 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5728 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5729 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005730 return InvalidBaseOK &&
5731 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005732 return Success(RVal, E);
5733 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005734 }
5735
Richard Smith11562c52011-10-28 17:51:58 +00005736 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005737}
Chris Lattner05706e882008-07-11 18:11:29 +00005738
Hal Finkel0dd05d42014-10-03 17:18:37 +00005739static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5740 // C++ [expr.alignof]p3:
5741 // When alignof is applied to a reference type, the result is the
5742 // alignment of the referenced type.
5743 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5744 T = Ref->getPointeeType();
5745
5746 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005747 if (T.getQualifiers().hasUnaligned())
5748 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005749 return Info.Ctx.toCharUnitsFromBits(
5750 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5751}
5752
5753static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5754 E = E->IgnoreParens();
5755
5756 // The kinds of expressions that we have special-case logic here for
5757 // should be kept up to date with the special checks for those
5758 // expressions in Sema.
5759
5760 // alignof decl is always accepted, even if it doesn't make sense: we default
5761 // to 1 in those cases.
5762 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5763 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5764 /*RefAsPointee*/true);
5765
5766 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5767 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5768 /*RefAsPointee*/true);
5769
5770 return GetAlignOfType(Info, E->getType());
5771}
5772
George Burgess IVe3763372016-12-22 02:50:20 +00005773// To be clear: this happily visits unsupported builtins. Better name welcomed.
5774bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5775 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5776 return true;
5777
George Burgess IVf9013bf2017-02-10 22:52:29 +00005778 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005779 return false;
5780
5781 Result.setInvalid(E);
5782 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Martin Bohme542c84b2017-08-30 10:44:46 +00005783 Result.addUnsizedArray(Info, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00005784 return true;
5785}
5786
Peter Collingbournee9200682011-05-13 03:29:01 +00005787bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005788 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005789 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005790
Richard Smith6328cbd2016-11-16 00:57:23 +00005791 if (unsigned BuiltinOp = E->getBuiltinCallee())
5792 return VisitBuiltinCallExpr(E, BuiltinOp);
5793
George Burgess IVe3763372016-12-22 02:50:20 +00005794 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005795}
5796
5797bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5798 unsigned BuiltinOp) {
5799 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005800 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005801 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005802 case Builtin::BI__builtin_assume_aligned: {
5803 // We need to be very careful here because: if the pointer does not have the
5804 // asserted alignment, then the behavior is undefined, and undefined
5805 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005806 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005807 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005808
Hal Finkel0dd05d42014-10-03 17:18:37 +00005809 LValue OffsetResult(Result);
5810 APSInt Alignment;
5811 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5812 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005813 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005814
5815 if (E->getNumArgs() > 2) {
5816 APSInt Offset;
5817 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5818 return false;
5819
Richard Smith642a2362017-01-30 23:30:26 +00005820 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005821 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5822 }
5823
5824 // If there is a base object, then it must have the correct alignment.
5825 if (OffsetResult.Base) {
5826 CharUnits BaseAlignment;
5827 if (const ValueDecl *VD =
5828 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5829 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5830 } else {
5831 BaseAlignment =
5832 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5833 }
5834
5835 if (BaseAlignment < Align) {
5836 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005837 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005838 CCEDiag(E->getArg(0),
5839 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005840 << (unsigned)BaseAlignment.getQuantity()
5841 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005842 return false;
5843 }
5844 }
5845
5846 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005847 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005848 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005849
Richard Smith642a2362017-01-30 23:30:26 +00005850 (OffsetResult.Base
5851 ? CCEDiag(E->getArg(0),
5852 diag::note_constexpr_baa_insufficient_alignment) << 1
5853 : CCEDiag(E->getArg(0),
5854 diag::note_constexpr_baa_value_insufficient_alignment))
5855 << (int)OffsetResult.Offset.getQuantity()
5856 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005857 return false;
5858 }
5859
5860 return true;
5861 }
Richard Smithe9507952016-11-12 01:39:56 +00005862
5863 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005864 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005865 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005866 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005867 if (Info.getLangOpts().CPlusPlus11)
5868 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5869 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005870 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005871 else
5872 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5873 // Fall through.
5874 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005875 case Builtin::BI__builtin_wcschr:
5876 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005877 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005878 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005879 if (!Visit(E->getArg(0)))
5880 return false;
5881 APSInt Desired;
5882 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5883 return false;
5884 uint64_t MaxLength = uint64_t(-1);
5885 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005886 BuiltinOp != Builtin::BIwcschr &&
5887 BuiltinOp != Builtin::BI__builtin_strchr &&
5888 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005889 APSInt N;
5890 if (!EvaluateInteger(E->getArg(2), N, Info))
5891 return false;
5892 MaxLength = N.getExtValue();
5893 }
5894
Richard Smith8110c9d2016-11-29 19:45:17 +00005895 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005896
Richard Smith8110c9d2016-11-29 19:45:17 +00005897 // Figure out what value we're actually looking for (after converting to
5898 // the corresponding unsigned type if necessary).
5899 uint64_t DesiredVal;
5900 bool StopAtNull = false;
5901 switch (BuiltinOp) {
5902 case Builtin::BIstrchr:
5903 case Builtin::BI__builtin_strchr:
5904 // strchr compares directly to the passed integer, and therefore
5905 // always fails if given an int that is not a char.
5906 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5907 E->getArg(1)->getType(),
5908 Desired),
5909 Desired))
5910 return ZeroInitialization(E);
5911 StopAtNull = true;
5912 // Fall through.
5913 case Builtin::BImemchr:
5914 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005915 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005916 // memchr compares by converting both sides to unsigned char. That's also
5917 // correct for strchr if we get this far (to cope with plain char being
5918 // unsigned in the strchr case).
5919 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5920 break;
Richard Smithe9507952016-11-12 01:39:56 +00005921
Richard Smith8110c9d2016-11-29 19:45:17 +00005922 case Builtin::BIwcschr:
5923 case Builtin::BI__builtin_wcschr:
5924 StopAtNull = true;
5925 // Fall through.
5926 case Builtin::BIwmemchr:
5927 case Builtin::BI__builtin_wmemchr:
5928 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5929 DesiredVal = Desired.getZExtValue();
5930 break;
5931 }
Richard Smithe9507952016-11-12 01:39:56 +00005932
5933 for (; MaxLength; --MaxLength) {
5934 APValue Char;
5935 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5936 !Char.isInt())
5937 return false;
5938 if (Char.getInt().getZExtValue() == DesiredVal)
5939 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005940 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005941 break;
5942 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5943 return false;
5944 }
5945 // Not found: return nullptr.
5946 return ZeroInitialization(E);
5947 }
5948
Richard Smith6cbd65d2013-07-11 02:27:57 +00005949 default:
George Burgess IVe3763372016-12-22 02:50:20 +00005950 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005951 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005952}
Chris Lattner05706e882008-07-11 18:11:29 +00005953
5954//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005955// Member Pointer Evaluation
5956//===----------------------------------------------------------------------===//
5957
5958namespace {
5959class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005960 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005961 MemberPtr &Result;
5962
5963 bool Success(const ValueDecl *D) {
5964 Result = MemberPtr(D);
5965 return true;
5966 }
5967public:
5968
5969 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5970 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5971
Richard Smith2e312c82012-03-03 22:46:17 +00005972 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005973 Result.setFrom(V);
5974 return true;
5975 }
Richard Smithfddd3842011-12-30 21:15:51 +00005976 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005977 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005978 }
5979
5980 bool VisitCastExpr(const CastExpr *E);
5981 bool VisitUnaryAddrOf(const UnaryOperator *E);
5982};
5983} // end anonymous namespace
5984
5985static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5986 EvalInfo &Info) {
5987 assert(E->isRValue() && E->getType()->isMemberPointerType());
5988 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5989}
5990
5991bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5992 switch (E->getCastKind()) {
5993 default:
5994 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5995
5996 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005997 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005998 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005999
6000 case CK_BaseToDerivedMemberPointer: {
6001 if (!Visit(E->getSubExpr()))
6002 return false;
6003 if (E->path_empty())
6004 return true;
6005 // Base-to-derived member pointer casts store the path in derived-to-base
6006 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6007 // the wrong end of the derived->base arc, so stagger the path by one class.
6008 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6009 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6010 PathI != PathE; ++PathI) {
6011 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6012 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6013 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006014 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006015 }
6016 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6017 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006018 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006019 return true;
6020 }
6021
6022 case CK_DerivedToBaseMemberPointer:
6023 if (!Visit(E->getSubExpr()))
6024 return false;
6025 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6026 PathE = E->path_end(); PathI != PathE; ++PathI) {
6027 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6028 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6029 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006030 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006031 }
6032 return true;
6033 }
6034}
6035
6036bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6037 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6038 // member can be formed.
6039 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6040}
6041
6042//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006043// Record Evaluation
6044//===----------------------------------------------------------------------===//
6045
6046namespace {
6047 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006048 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006049 const LValue &This;
6050 APValue &Result;
6051 public:
6052
6053 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6054 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6055
Richard Smith2e312c82012-03-03 22:46:17 +00006056 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006057 Result = V;
6058 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006059 }
Richard Smithb8348f52016-05-12 22:16:28 +00006060 bool ZeroInitialization(const Expr *E) {
6061 return ZeroInitialization(E, E->getType());
6062 }
6063 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006064
Richard Smith52a980a2015-08-28 02:43:42 +00006065 bool VisitCallExpr(const CallExpr *E) {
6066 return handleCallExpr(E, Result, &This);
6067 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006068 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006069 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006070 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6071 return VisitCXXConstructExpr(E, E->getType());
6072 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006073 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006074 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006075 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006076 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006077 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006078}
Richard Smithd62306a2011-11-10 06:34:14 +00006079
Richard Smithfddd3842011-12-30 21:15:51 +00006080/// Perform zero-initialization on an object of non-union class type.
6081/// C++11 [dcl.init]p5:
6082/// To zero-initialize an object or reference of type T means:
6083/// [...]
6084/// -- if T is a (possibly cv-qualified) non-union class type,
6085/// each non-static data member and each base-class subobject is
6086/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006087static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6088 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006089 const LValue &This, APValue &Result) {
6090 assert(!RD->isUnion() && "Expected non-union class type");
6091 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6092 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006093 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006094
John McCalld7bca762012-05-01 00:38:49 +00006095 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006096 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6097
6098 if (CD) {
6099 unsigned Index = 0;
6100 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006101 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006102 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6103 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006104 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6105 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006106 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006107 Result.getStructBase(Index)))
6108 return false;
6109 }
6110 }
6111
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006112 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006113 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006114 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006115 continue;
6116
6117 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006118 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006119 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006120
David Blaikie2d7c57e2012-04-30 02:36:29 +00006121 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006122 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006123 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006124 return false;
6125 }
6126
6127 return true;
6128}
6129
Richard Smithb8348f52016-05-12 22:16:28 +00006130bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6131 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006132 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006133 if (RD->isUnion()) {
6134 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6135 // object's first non-static named data member is zero-initialized
6136 RecordDecl::field_iterator I = RD->field_begin();
6137 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006138 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006139 return true;
6140 }
6141
6142 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006143 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006144 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006145 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006146 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006147 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006148 }
6149
Richard Smith5d108602012-02-17 00:44:16 +00006150 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006151 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006152 return false;
6153 }
6154
Richard Smitha8105bc2012-01-06 16:39:00 +00006155 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006156}
6157
Richard Smithe97cbd72011-11-11 04:05:33 +00006158bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6159 switch (E->getCastKind()) {
6160 default:
6161 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6162
6163 case CK_ConstructorConversion:
6164 return Visit(E->getSubExpr());
6165
6166 case CK_DerivedToBase:
6167 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006168 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006169 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006170 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006171 if (!DerivedObject.isStruct())
6172 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006173
6174 // Derived-to-base rvalue conversion: just slice off the derived part.
6175 APValue *Value = &DerivedObject;
6176 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6177 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6178 PathE = E->path_end(); PathI != PathE; ++PathI) {
6179 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6180 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6181 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6182 RD = Base;
6183 }
6184 Result = *Value;
6185 return true;
6186 }
6187 }
6188}
6189
Richard Smithd62306a2011-11-10 06:34:14 +00006190bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006191 if (E->isTransparent())
6192 return Visit(E->getInit(0));
6193
Richard Smithd62306a2011-11-10 06:34:14 +00006194 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006195 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006196 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6197
6198 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006199 const FieldDecl *Field = E->getInitializedFieldInUnion();
6200 Result = APValue(Field);
6201 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006202 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006203
6204 // If the initializer list for a union does not contain any elements, the
6205 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006206 // FIXME: The element should be initialized from an initializer list.
6207 // Is this difference ever observable for initializer lists which
6208 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006209 ImplicitValueInitExpr VIE(Field->getType());
6210 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6211
Richard Smithd62306a2011-11-10 06:34:14 +00006212 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006213 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6214 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006215
6216 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6217 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6218 isa<CXXDefaultInitExpr>(InitExpr));
6219
Richard Smithb228a862012-02-15 02:18:13 +00006220 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006221 }
6222
Richard Smith872307e2016-03-08 22:17:41 +00006223 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006224 if (Result.isUninit())
6225 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6226 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006227 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006228 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006229
6230 // Initialize base classes.
6231 if (CXXRD) {
6232 for (const auto &Base : CXXRD->bases()) {
6233 assert(ElementNo < E->getNumInits() && "missing init for base class");
6234 const Expr *Init = E->getInit(ElementNo);
6235
6236 LValue Subobject = This;
6237 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6238 return false;
6239
6240 APValue &FieldVal = Result.getStructBase(ElementNo);
6241 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006242 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006243 return false;
6244 Success = false;
6245 }
6246 ++ElementNo;
6247 }
6248 }
6249
6250 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006251 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006252 // Anonymous bit-fields are not considered members of the class for
6253 // purposes of aggregate initialization.
6254 if (Field->isUnnamedBitfield())
6255 continue;
6256
6257 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006258
Richard Smith253c2a32012-01-27 01:14:48 +00006259 bool HaveInit = ElementNo < E->getNumInits();
6260
6261 // FIXME: Diagnostics here should point to the end of the initializer
6262 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006263 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006264 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006265 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006266
6267 // Perform an implicit value-initialization for members beyond the end of
6268 // the initializer list.
6269 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006270 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006271
Richard Smith852c9db2013-04-20 22:23:05 +00006272 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6273 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6274 isa<CXXDefaultInitExpr>(Init));
6275
Richard Smith49ca8aa2013-08-06 07:09:20 +00006276 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6277 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6278 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006279 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006280 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006281 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006282 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006283 }
6284 }
6285
Richard Smith253c2a32012-01-27 01:14:48 +00006286 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006287}
6288
Richard Smithb8348f52016-05-12 22:16:28 +00006289bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6290 QualType T) {
6291 // Note that E's type is not necessarily the type of our class here; we might
6292 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006293 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006294 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6295
Richard Smithfddd3842011-12-30 21:15:51 +00006296 bool ZeroInit = E->requiresZeroInitialization();
6297 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006298 // If we've already performed zero-initialization, we're already done.
6299 if (!Result.isUninit())
6300 return true;
6301
Richard Smithda3f4fd2014-03-05 23:32:50 +00006302 // We can get here in two different ways:
6303 // 1) We're performing value-initialization, and should zero-initialize
6304 // the object, or
6305 // 2) We're performing default-initialization of an object with a trivial
6306 // constexpr default constructor, in which case we should start the
6307 // lifetimes of all the base subobjects (there can be no data member
6308 // subobjects in this case) per [basic.life]p1.
6309 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006310 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006311 }
6312
Craig Topper36250ad2014-05-12 05:36:57 +00006313 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006314 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006315
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006316 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006317 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006318
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006319 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006320 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006321 if (const MaterializeTemporaryExpr *ME
6322 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6323 return Visit(ME->GetTemporaryExpr());
6324
Richard Smithb8348f52016-05-12 22:16:28 +00006325 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006326 return false;
6327
Craig Topper5fc8fc22014-08-27 06:28:36 +00006328 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006329 return HandleConstructorCall(E, This, Args,
6330 cast<CXXConstructorDecl>(Definition), Info,
6331 Result);
6332}
6333
6334bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6335 const CXXInheritedCtorInitExpr *E) {
6336 if (!Info.CurrentCall) {
6337 assert(Info.checkingPotentialConstantExpression());
6338 return false;
6339 }
6340
6341 const CXXConstructorDecl *FD = E->getConstructor();
6342 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6343 return false;
6344
6345 const FunctionDecl *Definition = nullptr;
6346 auto Body = FD->getBody(Definition);
6347
6348 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6349 return false;
6350
6351 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006352 cast<CXXConstructorDecl>(Definition), Info,
6353 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006354}
6355
Richard Smithcc1b96d2013-06-12 22:31:48 +00006356bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6357 const CXXStdInitializerListExpr *E) {
6358 const ConstantArrayType *ArrayType =
6359 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6360
6361 LValue Array;
6362 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6363 return false;
6364
6365 // Get a pointer to the first element of the array.
6366 Array.addArray(Info, E, ArrayType);
6367
6368 // FIXME: Perform the checks on the field types in SemaInit.
6369 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6370 RecordDecl::field_iterator Field = Record->field_begin();
6371 if (Field == Record->field_end())
6372 return Error(E);
6373
6374 // Start pointer.
6375 if (!Field->getType()->isPointerType() ||
6376 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6377 ArrayType->getElementType()))
6378 return Error(E);
6379
6380 // FIXME: What if the initializer_list type has base classes, etc?
6381 Result = APValue(APValue::UninitStruct(), 0, 2);
6382 Array.moveInto(Result.getStructField(0));
6383
6384 if (++Field == Record->field_end())
6385 return Error(E);
6386
6387 if (Field->getType()->isPointerType() &&
6388 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6389 ArrayType->getElementType())) {
6390 // End pointer.
6391 if (!HandleLValueArrayAdjustment(Info, E, Array,
6392 ArrayType->getElementType(),
6393 ArrayType->getSize().getZExtValue()))
6394 return false;
6395 Array.moveInto(Result.getStructField(1));
6396 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6397 // Length.
6398 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6399 else
6400 return Error(E);
6401
6402 if (++Field != Record->field_end())
6403 return Error(E);
6404
6405 return true;
6406}
6407
Faisal Valic72a08c2017-01-09 03:02:53 +00006408bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6409 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6410 if (ClosureClass->isInvalidDecl()) return false;
6411
6412 if (Info.checkingPotentialConstantExpression()) return true;
Daniel Jasperffdee092017-05-02 19:21:42 +00006413
Faisal Vali051e3a22017-02-16 04:12:21 +00006414 const size_t NumFields =
6415 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006416
6417 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6418 E->capture_init_end()) &&
6419 "The number of lambda capture initializers should equal the number of "
6420 "fields within the closure type");
6421
Faisal Vali051e3a22017-02-16 04:12:21 +00006422 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6423 // Iterate through all the lambda's closure object's fields and initialize
6424 // them.
6425 auto *CaptureInitIt = E->capture_init_begin();
6426 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6427 bool Success = true;
6428 for (const auto *Field : ClosureClass->fields()) {
6429 assert(CaptureInitIt != E->capture_init_end());
6430 // Get the initializer for this field
6431 Expr *const CurFieldInit = *CaptureInitIt++;
Daniel Jasperffdee092017-05-02 19:21:42 +00006432
Faisal Vali051e3a22017-02-16 04:12:21 +00006433 // If there is no initializer, either this is a VLA or an error has
6434 // occurred.
6435 if (!CurFieldInit)
6436 return Error(E);
6437
6438 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6439 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6440 if (!Info.keepEvaluatingAfterFailure())
6441 return false;
6442 Success = false;
6443 }
6444 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006445 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006446 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006447}
6448
Richard Smithd62306a2011-11-10 06:34:14 +00006449static bool EvaluateRecord(const Expr *E, const LValue &This,
6450 APValue &Result, EvalInfo &Info) {
6451 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006452 "can't evaluate expression as a record rvalue");
6453 return RecordExprEvaluator(Info, This, Result).Visit(E);
6454}
6455
6456//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006457// Temporary Evaluation
6458//
6459// Temporaries are represented in the AST as rvalues, but generally behave like
6460// lvalues. The full-object of which the temporary is a subobject is implicitly
6461// materialized so that a reference can bind to it.
6462//===----------------------------------------------------------------------===//
6463namespace {
6464class TemporaryExprEvaluator
6465 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6466public:
6467 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006468 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006469
6470 /// Visit an expression which constructs the value of this temporary.
6471 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006472 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006473 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6474 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006475 }
6476
6477 bool VisitCastExpr(const CastExpr *E) {
6478 switch (E->getCastKind()) {
6479 default:
6480 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6481
6482 case CK_ConstructorConversion:
6483 return VisitConstructExpr(E->getSubExpr());
6484 }
6485 }
6486 bool VisitInitListExpr(const InitListExpr *E) {
6487 return VisitConstructExpr(E);
6488 }
6489 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6490 return VisitConstructExpr(E);
6491 }
6492 bool VisitCallExpr(const CallExpr *E) {
6493 return VisitConstructExpr(E);
6494 }
Richard Smith513955c2014-12-17 19:24:30 +00006495 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6496 return VisitConstructExpr(E);
6497 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006498 bool VisitLambdaExpr(const LambdaExpr *E) {
6499 return VisitConstructExpr(E);
6500 }
Richard Smith027bf112011-11-17 22:56:20 +00006501};
6502} // end anonymous namespace
6503
6504/// Evaluate an expression of record type as a temporary.
6505static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006506 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006507 return TemporaryExprEvaluator(Info, Result).Visit(E);
6508}
6509
6510//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006511// Vector Evaluation
6512//===----------------------------------------------------------------------===//
6513
6514namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006515 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006516 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006517 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006518 public:
Mike Stump11289f42009-09-09 15:08:12 +00006519
Richard Smith2d406342011-10-22 21:10:00 +00006520 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6521 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006522
Craig Topper9798b932015-09-29 04:30:05 +00006523 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006524 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6525 // FIXME: remove this APValue copy.
6526 Result = APValue(V.data(), V.size());
6527 return true;
6528 }
Richard Smith2e312c82012-03-03 22:46:17 +00006529 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006530 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006531 Result = V;
6532 return true;
6533 }
Richard Smithfddd3842011-12-30 21:15:51 +00006534 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006535
Richard Smith2d406342011-10-22 21:10:00 +00006536 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006537 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006538 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006539 bool VisitInitListExpr(const InitListExpr *E);
6540 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006541 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006542 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006543 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006544 };
6545} // end anonymous namespace
6546
6547static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006548 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006549 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006550}
6551
George Burgess IV533ff002015-12-11 00:23:35 +00006552bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006553 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006554 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006555
Richard Smith161f09a2011-12-06 22:44:34 +00006556 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006557 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006558
Eli Friedmanc757de22011-03-25 00:43:55 +00006559 switch (E->getCastKind()) {
6560 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006561 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006562 if (SETy->isIntegerType()) {
6563 APSInt IntResult;
6564 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006565 return false;
6566 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006567 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006568 APFloat FloatResult(0.0);
6569 if (!EvaluateFloat(SE, FloatResult, Info))
6570 return false;
6571 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006572 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006573 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006574 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006575
6576 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006577 SmallVector<APValue, 4> Elts(NElts, Val);
6578 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006579 }
Eli Friedman803acb32011-12-22 03:51:45 +00006580 case CK_BitCast: {
6581 // Evaluate the operand into an APInt we can extract from.
6582 llvm::APInt SValInt;
6583 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6584 return false;
6585 // Extract the elements
6586 QualType EltTy = VTy->getElementType();
6587 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6588 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6589 SmallVector<APValue, 4> Elts;
6590 if (EltTy->isRealFloatingType()) {
6591 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006592 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006593 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006594 FloatEltSize = 80;
6595 for (unsigned i = 0; i < NElts; i++) {
6596 llvm::APInt Elt;
6597 if (BigEndian)
6598 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6599 else
6600 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006601 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006602 }
6603 } else if (EltTy->isIntegerType()) {
6604 for (unsigned i = 0; i < NElts; i++) {
6605 llvm::APInt Elt;
6606 if (BigEndian)
6607 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6608 else
6609 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6610 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6611 }
6612 } else {
6613 return Error(E);
6614 }
6615 return Success(Elts, E);
6616 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006617 default:
Richard Smith11562c52011-10-28 17:51:58 +00006618 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006619 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006620}
6621
Richard Smith2d406342011-10-22 21:10:00 +00006622bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006623VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006624 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006625 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006626 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006627
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006628 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006629 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006630
Eli Friedmanb9c71292012-01-03 23:24:20 +00006631 // The number of initializers can be less than the number of
6632 // vector elements. For OpenCL, this can be due to nested vector
Daniel Jasperffdee092017-05-02 19:21:42 +00006633 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00006634 // should be initialized with zeroes.
6635 unsigned CountInits = 0, CountElts = 0;
6636 while (CountElts < NumElements) {
6637 // Handle nested vector initialization.
Daniel Jasperffdee092017-05-02 19:21:42 +00006638 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006639 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006640 APValue v;
6641 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6642 return Error(E);
6643 unsigned vlen = v.getVectorLength();
Daniel Jasperffdee092017-05-02 19:21:42 +00006644 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00006645 Elements.push_back(v.getVectorElt(j));
6646 CountElts += vlen;
6647 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006648 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006649 if (CountInits < NumInits) {
6650 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006651 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006652 } else // trailing integer zero.
6653 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6654 Elements.push_back(APValue(sInt));
6655 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006656 } else {
6657 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006658 if (CountInits < NumInits) {
6659 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006660 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006661 } else // trailing float zero.
6662 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6663 Elements.push_back(APValue(f));
6664 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006665 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006666 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006667 }
Richard Smith2d406342011-10-22 21:10:00 +00006668 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006669}
6670
Richard Smith2d406342011-10-22 21:10:00 +00006671bool
Richard Smithfddd3842011-12-30 21:15:51 +00006672VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006673 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006674 QualType EltTy = VT->getElementType();
6675 APValue ZeroElement;
6676 if (EltTy->isIntegerType())
6677 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6678 else
6679 ZeroElement =
6680 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6681
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006682 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006683 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006684}
6685
Richard Smith2d406342011-10-22 21:10:00 +00006686bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006687 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006688 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006689}
6690
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006691//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006692// Array Evaluation
6693//===----------------------------------------------------------------------===//
6694
6695namespace {
6696 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006697 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006698 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006699 APValue &Result;
6700 public:
6701
Richard Smithd62306a2011-11-10 06:34:14 +00006702 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6703 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006704
6705 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006706 assert((V.isArray() || V.isLValue()) &&
6707 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006708 Result = V;
6709 return true;
6710 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006711
Richard Smithfddd3842011-12-30 21:15:51 +00006712 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006713 const ConstantArrayType *CAT =
6714 Info.Ctx.getAsConstantArrayType(E->getType());
6715 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006716 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006717
6718 Result = APValue(APValue::UninitArray(), 0,
6719 CAT->getSize().getZExtValue());
6720 if (!Result.hasArrayFiller()) return true;
6721
Richard Smithfddd3842011-12-30 21:15:51 +00006722 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006723 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006724 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006725 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006726 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006727 }
6728
Richard Smith52a980a2015-08-28 02:43:42 +00006729 bool VisitCallExpr(const CallExpr *E) {
6730 return handleCallExpr(E, Result, &This);
6731 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006732 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006733 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006734 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006735 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6736 const LValue &Subobject,
6737 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006738 };
6739} // end anonymous namespace
6740
Richard Smithd62306a2011-11-10 06:34:14 +00006741static bool EvaluateArray(const Expr *E, const LValue &This,
6742 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006743 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006744 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006745}
6746
6747bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6748 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6749 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006750 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006751
Richard Smithca2cfbf2011-12-22 01:07:19 +00006752 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6753 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006754 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006755 LValue LV;
6756 if (!EvaluateLValue(E->getInit(0), LV, Info))
6757 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006758 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006759 LV.moveInto(Val);
6760 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006761 }
6762
Richard Smith253c2a32012-01-27 01:14:48 +00006763 bool Success = true;
6764
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006765 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6766 "zero-initialized array shouldn't have any initialized elts");
6767 APValue Filler;
6768 if (Result.isArray() && Result.hasArrayFiller())
6769 Filler = Result.getArrayFiller();
6770
Richard Smith9543c5e2013-04-22 14:44:29 +00006771 unsigned NumEltsToInit = E->getNumInits();
6772 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006773 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006774
6775 // If the initializer might depend on the array index, run it for each
6776 // array element. For now, just whitelist non-class value-initialization.
6777 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6778 NumEltsToInit = NumElts;
6779
6780 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006781
6782 // If the array was previously zero-initialized, preserve the
6783 // zero-initialized values.
6784 if (!Filler.isUninit()) {
6785 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6786 Result.getArrayInitializedElt(I) = Filler;
6787 if (Result.hasArrayFiller())
6788 Result.getArrayFiller() = Filler;
6789 }
6790
Richard Smithd62306a2011-11-10 06:34:14 +00006791 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006792 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006793 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6794 const Expr *Init =
6795 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006796 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006797 Info, Subobject, Init) ||
6798 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006799 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006800 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006801 return false;
6802 Success = false;
6803 }
Richard Smithd62306a2011-11-10 06:34:14 +00006804 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006805
Richard Smith9543c5e2013-04-22 14:44:29 +00006806 if (!Result.hasArrayFiller())
6807 return Success;
6808
6809 // If we get here, we have a trivial filler, which we can just evaluate
6810 // once and splat over the rest of the array elements.
6811 assert(FillerExpr && "no array filler for incomplete init list");
6812 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6813 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006814}
6815
Richard Smith410306b2016-12-12 02:53:20 +00006816bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6817 if (E->getCommonExpr() &&
6818 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6819 Info, E->getCommonExpr()->getSourceExpr()))
6820 return false;
6821
6822 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6823
6824 uint64_t Elements = CAT->getSize().getZExtValue();
6825 Result = APValue(APValue::UninitArray(), Elements, Elements);
6826
6827 LValue Subobject = This;
6828 Subobject.addArray(Info, E, CAT);
6829
6830 bool Success = true;
6831 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6832 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6833 Info, Subobject, E->getSubExpr()) ||
6834 !HandleLValueArrayAdjustment(Info, E, Subobject,
6835 CAT->getElementType(), 1)) {
6836 if (!Info.noteFailure())
6837 return false;
6838 Success = false;
6839 }
6840 }
6841
6842 return Success;
6843}
6844
Richard Smith027bf112011-11-17 22:56:20 +00006845bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006846 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6847}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006848
Richard Smith9543c5e2013-04-22 14:44:29 +00006849bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6850 const LValue &Subobject,
6851 APValue *Value,
6852 QualType Type) {
6853 bool HadZeroInit = !Value->isUninit();
6854
6855 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6856 unsigned N = CAT->getSize().getZExtValue();
6857
6858 // Preserve the array filler if we had prior zero-initialization.
6859 APValue Filler =
6860 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6861 : APValue();
6862
6863 *Value = APValue(APValue::UninitArray(), N, N);
6864
6865 if (HadZeroInit)
6866 for (unsigned I = 0; I != N; ++I)
6867 Value->getArrayInitializedElt(I) = Filler;
6868
6869 // Initialize the elements.
6870 LValue ArrayElt = Subobject;
6871 ArrayElt.addArray(Info, E, CAT);
6872 for (unsigned I = 0; I != N; ++I)
6873 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6874 CAT->getElementType()) ||
6875 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6876 CAT->getElementType(), 1))
6877 return false;
6878
6879 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006880 }
Richard Smith027bf112011-11-17 22:56:20 +00006881
Richard Smith9543c5e2013-04-22 14:44:29 +00006882 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006883 return Error(E);
6884
Richard Smithb8348f52016-05-12 22:16:28 +00006885 return RecordExprEvaluator(Info, Subobject, *Value)
6886 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006887}
6888
Richard Smithf3e9e432011-11-07 09:22:26 +00006889//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006890// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006891//
6892// As a GNU extension, we support casting pointers to sufficiently-wide integer
6893// types and back in constant folding. Integer values are thus represented
6894// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006895//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006896
6897namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006898class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006899 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006900 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006901public:
Richard Smith2e312c82012-03-03 22:46:17 +00006902 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006903 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006904
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006905 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006906 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006907 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006908 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006909 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006910 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006911 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006912 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006913 return true;
6914 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006915 bool Success(const llvm::APSInt &SI, const Expr *E) {
6916 return Success(SI, E, Result);
6917 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006918
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006919 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00006920 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006921 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006922 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006923 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006924 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006925 Result.getInt().setIsUnsigned(
6926 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006927 return true;
6928 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006929 bool Success(const llvm::APInt &I, const Expr *E) {
6930 return Success(I, E, Result);
6931 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006932
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006933 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00006934 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006935 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006936 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006937 return true;
6938 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006939 bool Success(uint64_t Value, const Expr *E) {
6940 return Success(Value, E, Result);
6941 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006942
Ken Dyckdbc01912011-03-11 02:13:43 +00006943 bool Success(CharUnits Size, const Expr *E) {
6944 return Success(Size.getQuantity(), E);
6945 }
6946
Richard Smith2e312c82012-03-03 22:46:17 +00006947 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006948 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006949 Result = V;
6950 return true;
6951 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006952 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006953 }
Mike Stump11289f42009-09-09 15:08:12 +00006954
Richard Smithfddd3842011-12-30 21:15:51 +00006955 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006956
Peter Collingbournee9200682011-05-13 03:29:01 +00006957 //===--------------------------------------------------------------------===//
6958 // Visitor Methods
6959 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006960
Chris Lattner7174bf32008-07-12 00:38:25 +00006961 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006962 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006963 }
6964 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006965 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006966 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006967
6968 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6969 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006970 if (CheckReferencedDecl(E, E->getDecl()))
6971 return true;
6972
6973 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006974 }
6975 bool VisitMemberExpr(const MemberExpr *E) {
6976 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006977 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006978 return true;
6979 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006980
6981 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006982 }
6983
Peter Collingbournee9200682011-05-13 03:29:01 +00006984 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006985 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006986 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006987 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006988 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006989
Peter Collingbournee9200682011-05-13 03:29:01 +00006990 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006991 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006992
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006993 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006994 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006995 }
Mike Stump11289f42009-09-09 15:08:12 +00006996
Ted Kremeneke65b0862012-03-06 20:05:56 +00006997 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6998 return Success(E->getValue(), E);
6999 }
Richard Smith410306b2016-12-12 02:53:20 +00007000
7001 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7002 if (Info.ArrayInitIndex == uint64_t(-1)) {
7003 // We were asked to evaluate this subexpression independent of the
7004 // enclosing ArrayInitLoopExpr. We can't do that.
7005 Info.FFDiag(E);
7006 return false;
7007 }
7008 return Success(Info.ArrayInitIndex, E);
7009 }
Daniel Jasperffdee092017-05-02 19:21:42 +00007010
Richard Smith4ce706a2011-10-11 21:43:33 +00007011 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007012 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007013 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007014 }
7015
Douglas Gregor29c42f22012-02-24 07:38:34 +00007016 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7017 return Success(E->getValue(), E);
7018 }
7019
John Wiegley6242b6a2011-04-28 00:16:57 +00007020 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7021 return Success(E->getValue(), E);
7022 }
7023
John Wiegleyf9f65842011-04-25 06:54:41 +00007024 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7025 return Success(E->getValue(), E);
7026 }
7027
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007028 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007029 bool VisitUnaryImag(const UnaryOperator *E);
7030
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007031 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007032 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007033
Eli Friedman4e7a2412009-02-27 04:45:43 +00007034 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007035};
Chris Lattner05706e882008-07-11 18:11:29 +00007036} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007037
Richard Smith11562c52011-10-28 17:51:58 +00007038/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7039/// produce either the integer value or a pointer.
7040///
7041/// GCC has a heinous extension which folds casts between pointer types and
7042/// pointer-sized integral types. We support this by allowing the evaluation of
7043/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7044/// Some simple arithmetic on such values is supported (they are treated much
7045/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007046static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007047 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007048 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007049 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007050}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007051
Richard Smithf57d8cb2011-12-09 22:58:01 +00007052static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007053 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007054 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007055 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007056 if (!Val.isInt()) {
7057 // FIXME: It would be better to produce the diagnostic for casting
7058 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007059 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007060 return false;
7061 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007062 Result = Val.getInt();
7063 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007064}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007065
Richard Smithf57d8cb2011-12-09 22:58:01 +00007066/// Check whether the given declaration can be directly converted to an integral
7067/// rvalue. If not, no diagnostic is produced; there are other things we can
7068/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007069bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007070 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007071 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007072 // Check for signedness/width mismatches between E type and ECD value.
7073 bool SameSign = (ECD->getInitVal().isSigned()
7074 == E->getType()->isSignedIntegerOrEnumerationType());
7075 bool SameWidth = (ECD->getInitVal().getBitWidth()
7076 == Info.Ctx.getIntWidth(E->getType()));
7077 if (SameSign && SameWidth)
7078 return Success(ECD->getInitVal(), E);
7079 else {
7080 // Get rid of mismatch (otherwise Success assertions will fail)
7081 // by computing a new value matching the type of E.
7082 llvm::APSInt Val = ECD->getInitVal();
7083 if (!SameSign)
7084 Val.setIsSigned(!ECD->getInitVal().isSigned());
7085 if (!SameWidth)
7086 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7087 return Success(Val, E);
7088 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007089 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007090 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007091}
7092
Chris Lattner86ee2862008-10-06 06:40:35 +00007093/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7094/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007095static int EvaluateBuiltinClassifyType(const CallExpr *E,
7096 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007097 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007098 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007099 enum gcc_type_class {
7100 no_type_class = -1,
7101 void_type_class, integer_type_class, char_type_class,
7102 enumeral_type_class, boolean_type_class,
7103 pointer_type_class, reference_type_class, offset_type_class,
7104 real_type_class, complex_type_class,
7105 function_type_class, method_type_class,
7106 record_type_class, union_type_class,
7107 array_type_class, string_type_class,
7108 lang_type_class
7109 };
Mike Stump11289f42009-09-09 15:08:12 +00007110
7111 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007112 // ideal, however it is what gcc does.
7113 if (E->getNumArgs() == 0)
7114 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007115
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007116 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7117 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7118
7119 switch (CanTy->getTypeClass()) {
7120#define TYPE(ID, BASE)
7121#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7122#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7123#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7124#include "clang/AST/TypeNodes.def"
7125 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7126
7127 case Type::Builtin:
7128 switch (BT->getKind()) {
7129#define BUILTIN_TYPE(ID, SINGLETON_ID)
7130#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7131#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7132#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7133#include "clang/AST/BuiltinTypes.def"
7134 case BuiltinType::Void:
7135 return void_type_class;
7136
7137 case BuiltinType::Bool:
7138 return boolean_type_class;
7139
7140 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7141 case BuiltinType::UChar:
7142 case BuiltinType::UShort:
7143 case BuiltinType::UInt:
7144 case BuiltinType::ULong:
7145 case BuiltinType::ULongLong:
7146 case BuiltinType::UInt128:
7147 return integer_type_class;
7148
7149 case BuiltinType::NullPtr:
7150 return pointer_type_class;
7151
7152 case BuiltinType::WChar_U:
7153 case BuiltinType::Char16:
7154 case BuiltinType::Char32:
7155 case BuiltinType::ObjCId:
7156 case BuiltinType::ObjCClass:
7157 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007158#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7159 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007160#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007161 case BuiltinType::OCLSampler:
7162 case BuiltinType::OCLEvent:
7163 case BuiltinType::OCLClkEvent:
7164 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007165 case BuiltinType::OCLReserveID:
7166 case BuiltinType::Dependent:
7167 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7168 };
7169
7170 case Type::Enum:
7171 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7172 break;
7173
7174 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007175 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007176 break;
7177
7178 case Type::MemberPointer:
7179 if (CanTy->isMemberDataPointerType())
7180 return offset_type_class;
7181 else {
7182 // We expect member pointers to be either data or function pointers,
7183 // nothing else.
7184 assert(CanTy->isMemberFunctionPointerType());
7185 return method_type_class;
7186 }
7187
7188 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007189 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007190
7191 case Type::FunctionNoProto:
7192 case Type::FunctionProto:
7193 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7194
7195 case Type::Record:
7196 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7197 switch (RT->getDecl()->getTagKind()) {
7198 case TagTypeKind::TTK_Struct:
7199 case TagTypeKind::TTK_Class:
7200 case TagTypeKind::TTK_Interface:
7201 return record_type_class;
7202
7203 case TagTypeKind::TTK_Enum:
7204 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7205
7206 case TagTypeKind::TTK_Union:
7207 return union_type_class;
7208 }
7209 }
David Blaikie83d382b2011-09-23 05:06:16 +00007210 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007211
7212 case Type::ConstantArray:
7213 case Type::VariableArray:
7214 case Type::IncompleteArray:
7215 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7216
7217 case Type::BlockPointer:
7218 case Type::LValueReference:
7219 case Type::RValueReference:
7220 case Type::Vector:
7221 case Type::ExtVector:
7222 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007223 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007224 case Type::ObjCObject:
7225 case Type::ObjCInterface:
7226 case Type::ObjCObjectPointer:
7227 case Type::Pipe:
7228 case Type::Atomic:
7229 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7230 }
7231
7232 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007233}
7234
Richard Smith5fab0c92011-12-28 19:48:30 +00007235/// EvaluateBuiltinConstantPForLValue - Determine the result of
7236/// __builtin_constant_p when applied to the given lvalue.
7237///
7238/// An lvalue is only "constant" if it is a pointer or reference to the first
7239/// character of a string literal.
7240template<typename LValue>
7241static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007242 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007243 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7244}
7245
7246/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7247/// GCC as we can manage.
7248static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7249 QualType ArgType = Arg->getType();
7250
7251 // __builtin_constant_p always has one operand. The rules which gcc follows
7252 // are not precisely documented, but are as follows:
7253 //
7254 // - If the operand is of integral, floating, complex or enumeration type,
7255 // and can be folded to a known value of that type, it returns 1.
7256 // - If the operand and can be folded to a pointer to the first character
7257 // of a string literal (or such a pointer cast to an integral type), it
7258 // returns 1.
7259 //
7260 // Otherwise, it returns 0.
7261 //
7262 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7263 // its support for this does not currently work.
7264 if (ArgType->isIntegralOrEnumerationType()) {
7265 Expr::EvalResult Result;
7266 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7267 return false;
7268
7269 APValue &V = Result.Val;
7270 if (V.getKind() == APValue::Int)
7271 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007272 if (V.getKind() == APValue::LValue)
7273 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007274 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7275 return Arg->isEvaluatable(Ctx);
7276 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7277 LValue LV;
7278 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007279 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007280 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7281 : EvaluatePointer(Arg, LV, Info)) &&
7282 !Status.HasSideEffects)
7283 return EvaluateBuiltinConstantPForLValue(LV);
7284 }
7285
7286 // Anything else isn't considered to be sufficiently constant.
7287 return false;
7288}
7289
John McCall95007602010-05-10 23:27:23 +00007290/// Retrieves the "underlying object type" of the given expression,
7291/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007292static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007293 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7294 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007295 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007296 } else if (const Expr *E = B.get<const Expr*>()) {
7297 if (isa<CompoundLiteralExpr>(E))
7298 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007299 }
7300
7301 return QualType();
7302}
7303
George Burgess IV3a03fab2015-09-04 21:28:13 +00007304/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007305/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007306/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007307/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7308///
7309/// Always returns an RValue with a pointer representation.
7310static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7311 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7312
7313 auto *NoParens = E->IgnoreParens();
7314 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007315 if (Cast == nullptr)
7316 return NoParens;
7317
7318 // We only conservatively allow a few kinds of casts, because this code is
7319 // inherently a simple solution that seeks to support the common case.
7320 auto CastKind = Cast->getCastKind();
7321 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7322 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007323 return NoParens;
7324
7325 auto *SubExpr = Cast->getSubExpr();
7326 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7327 return NoParens;
7328 return ignorePointerCastsAndParens(SubExpr);
7329}
7330
George Burgess IVa51c4072015-10-16 01:49:01 +00007331/// Checks to see if the given LValue's Designator is at the end of the LValue's
7332/// record layout. e.g.
7333/// struct { struct { int a, b; } fst, snd; } obj;
7334/// obj.fst // no
7335/// obj.snd // yes
7336/// obj.fst.a // no
7337/// obj.fst.b // no
7338/// obj.snd.a // no
7339/// obj.snd.b // yes
7340///
7341/// Please note: this function is specialized for how __builtin_object_size
7342/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007343///
Martin Bohme542c84b2017-08-30 10:44:46 +00007344/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007345static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7346 assert(!LVal.Designator.Invalid);
7347
George Burgess IV4168d752016-06-27 19:40:41 +00007348 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7349 const RecordDecl *Parent = FD->getParent();
7350 Invalid = Parent->isInvalidDecl();
7351 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007352 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007353 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007354 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7355 };
7356
7357 auto &Base = LVal.getLValueBase();
7358 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7359 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007360 bool Invalid;
7361 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7362 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007363 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007364 for (auto *FD : IFD->chain()) {
7365 bool Invalid;
7366 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7367 return Invalid;
7368 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007369 }
7370 }
7371
George Burgess IVe3763372016-12-22 02:50:20 +00007372 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007373 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007374 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Martin Bohme542c84b2017-08-30 10:44:46 +00007375 assert(isBaseAnAllocSizeCall(Base) &&
7376 "Unsized array in non-alloc_size call?");
7377 // If this is an alloc_size base, we should ignore the initial array index
George Burgess IVe3763372016-12-22 02:50:20 +00007378 ++I;
7379 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7380 }
7381
7382 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7383 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007384 if (BaseType->isArrayType()) {
7385 // Because __builtin_object_size treats arrays as objects, we can ignore
7386 // the index iff this is the last array in the Designator.
7387 if (I + 1 == E)
7388 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007389 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7390 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007391 if (Index + 1 != CAT->getSize())
7392 return false;
7393 BaseType = CAT->getElementType();
7394 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007395 const auto *CT = BaseType->castAs<ComplexType>();
7396 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007397 if (Index != 1)
7398 return false;
7399 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007400 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007401 bool Invalid;
7402 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7403 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007404 BaseType = FD->getType();
7405 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007406 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007407 return false;
7408 }
7409 }
7410 return true;
7411}
7412
George Burgess IVe3763372016-12-22 02:50:20 +00007413/// Tests to see if the LValue has a user-specified designator (that isn't
7414/// necessarily valid). Note that this always returns 'true' if the LValue has
7415/// an unsized array as its first designator entry, because there's currently no
7416/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007417static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007418 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007419 return false;
7420
George Burgess IVe3763372016-12-22 02:50:20 +00007421 if (!LVal.Designator.Entries.empty())
7422 return LVal.Designator.isMostDerivedAnUnsizedArray();
7423
George Burgess IVa51c4072015-10-16 01:49:01 +00007424 if (!LVal.InvalidBase)
7425 return true;
7426
George Burgess IVe3763372016-12-22 02:50:20 +00007427 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7428 // the LValueBase.
7429 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7430 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007431}
7432
George Burgess IVe3763372016-12-22 02:50:20 +00007433/// Attempts to detect a user writing into a piece of memory that's impossible
7434/// to figure out the size of by just using types.
7435static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7436 const SubobjectDesignator &Designator = LVal.Designator;
7437 // Notes:
7438 // - Users can only write off of the end when we have an invalid base. Invalid
7439 // bases imply we don't know where the memory came from.
7440 // - We used to be a bit more aggressive here; we'd only be conservative if
7441 // the array at the end was flexible, or if it had 0 or 1 elements. This
7442 // broke some common standard library extensions (PR30346), but was
7443 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7444 // with some sort of whitelist. OTOH, it seems that GCC is always
7445 // conservative with the last element in structs (if it's an array), so our
7446 // current behavior is more compatible than a whitelisting approach would
7447 // be.
7448 return LVal.InvalidBase &&
7449 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7450 Designator.MostDerivedIsArrayElement &&
7451 isDesignatorAtObjectEnd(Ctx, LVal);
7452}
7453
7454/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7455/// Fails if the conversion would cause loss of precision.
7456static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7457 CharUnits &Result) {
7458 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7459 if (Int.ugt(CharUnitsMax))
7460 return false;
7461 Result = CharUnits::fromQuantity(Int.getZExtValue());
7462 return true;
7463}
7464
7465/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7466/// determine how many bytes exist from the beginning of the object to either
7467/// the end of the current subobject, or the end of the object itself, depending
7468/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007469///
George Burgess IVe3763372016-12-22 02:50:20 +00007470/// If this returns false, the value of Result is undefined.
7471static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7472 unsigned Type, const LValue &LVal,
7473 CharUnits &EndOffset) {
7474 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007475
George Burgess IV7fb7e362017-01-03 23:35:19 +00007476 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7477 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7478 return false;
7479 return HandleSizeof(Info, ExprLoc, Ty, Result);
7480 };
7481
George Burgess IVe3763372016-12-22 02:50:20 +00007482 // We want to evaluate the size of the entire object. This is a valid fallback
7483 // for when Type=1 and the designator is invalid, because we're asked for an
7484 // upper-bound.
7485 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7486 // Type=3 wants a lower bound, so we can't fall back to this.
7487 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007488 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007489
7490 llvm::APInt APEndOffset;
7491 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7492 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7493 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7494
7495 if (LVal.InvalidBase)
7496 return false;
7497
7498 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007499 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007500 }
7501
George Burgess IVe3763372016-12-22 02:50:20 +00007502 // We want to evaluate the size of a subobject.
7503 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007504
7505 // The following is a moderately common idiom in C:
7506 //
7507 // struct Foo { int a; char c[1]; };
7508 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7509 // strcpy(&F->c[0], Bar);
7510 //
George Burgess IVe3763372016-12-22 02:50:20 +00007511 // In order to not break too much legacy code, we need to support it.
7512 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7513 // If we can resolve this to an alloc_size call, we can hand that back,
7514 // because we know for certain how many bytes there are to write to.
7515 llvm::APInt APEndOffset;
7516 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7517 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7518 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7519
7520 // If we cannot determine the size of the initial allocation, then we can't
7521 // given an accurate upper-bound. However, we are still able to give
7522 // conservative lower-bounds for Type=3.
7523 if (Type == 1)
7524 return false;
7525 }
7526
7527 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007528 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007529 return false;
7530
George Burgess IVe3763372016-12-22 02:50:20 +00007531 // According to the GCC documentation, we want the size of the subobject
7532 // denoted by the pointer. But that's not quite right -- what we actually
7533 // want is the size of the immediately-enclosing array, if there is one.
7534 int64_t ElemsRemaining;
7535 if (Designator.MostDerivedIsArrayElement &&
7536 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7537 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7538 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7539 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7540 } else {
7541 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7542 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007543
George Burgess IVe3763372016-12-22 02:50:20 +00007544 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7545 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007546}
7547
George Burgess IVe3763372016-12-22 02:50:20 +00007548/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7549/// returns true and stores the result in @p Size.
7550///
7551/// If @p WasError is non-null, this will report whether the failure to evaluate
7552/// is to be treated as an Error in IntExprEvaluator.
7553static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7554 EvalInfo &Info, uint64_t &Size) {
7555 // Determine the denoted object.
7556 LValue LVal;
7557 {
7558 // The operand of __builtin_object_size is never evaluated for side-effects.
7559 // If there are any, but we can determine the pointed-to object anyway, then
7560 // ignore the side-effects.
7561 SpeculativeEvaluationRAII SpeculativeEval(Info);
7562 FoldOffsetRAII Fold(Info);
7563
7564 if (E->isGLValue()) {
7565 // It's possible for us to be given GLValues if we're called via
7566 // Expr::tryEvaluateObjectSize.
7567 APValue RVal;
7568 if (!EvaluateAsRValue(Info, E, RVal))
7569 return false;
7570 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007571 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7572 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007573 return false;
7574 }
7575
7576 // If we point to before the start of the object, there are no accessible
7577 // bytes.
7578 if (LVal.getLValueOffset().isNegative()) {
7579 Size = 0;
7580 return true;
7581 }
7582
7583 CharUnits EndOffset;
7584 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7585 return false;
7586
7587 // If we've fallen outside of the end offset, just pretend there's nothing to
7588 // write to/read from.
7589 if (EndOffset <= LVal.getLValueOffset())
7590 Size = 0;
7591 else
7592 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7593 return true;
John McCall95007602010-05-10 23:27:23 +00007594}
7595
Peter Collingbournee9200682011-05-13 03:29:01 +00007596bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007597 if (unsigned BuiltinOp = E->getBuiltinCallee())
7598 return VisitBuiltinCallExpr(E, BuiltinOp);
7599
7600 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7601}
7602
7603bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7604 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007605 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007606 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007607 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007608
7609 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007610 // The type was checked when we built the expression.
7611 unsigned Type =
7612 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7613 assert(Type <= 3 && "unexpected type");
7614
George Burgess IVe3763372016-12-22 02:50:20 +00007615 uint64_t Size;
7616 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7617 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007618
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007619 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007620 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007621
Richard Smith01ade172012-05-23 04:13:20 +00007622 // Expression had no side effects, but we couldn't statically determine the
7623 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007624 switch (Info.EvalMode) {
7625 case EvalInfo::EM_ConstantExpression:
7626 case EvalInfo::EM_PotentialConstantExpression:
7627 case EvalInfo::EM_ConstantFold:
7628 case EvalInfo::EM_EvaluateForOverflow:
7629 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007630 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007631 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007632 return Error(E);
7633 case EvalInfo::EM_ConstantExpressionUnevaluated:
7634 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007635 // Reduce it to a constant now.
7636 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007637 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007638
7639 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007640 }
7641
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007642 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007643 case Builtin::BI__builtin_bswap32:
7644 case Builtin::BI__builtin_bswap64: {
7645 APSInt Val;
7646 if (!EvaluateInteger(E->getArg(0), Val, Info))
7647 return false;
7648
7649 return Success(Val.byteSwap(), E);
7650 }
7651
Richard Smith8889a3d2013-06-13 06:26:32 +00007652 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007653 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007654
7655 // FIXME: BI__builtin_clrsb
7656 // FIXME: BI__builtin_clrsbl
7657 // FIXME: BI__builtin_clrsbll
7658
Richard Smith80b3c8e2013-06-13 05:04:16 +00007659 case Builtin::BI__builtin_clz:
7660 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007661 case Builtin::BI__builtin_clzll:
7662 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007663 APSInt Val;
7664 if (!EvaluateInteger(E->getArg(0), Val, Info))
7665 return false;
7666 if (!Val)
7667 return Error(E);
7668
7669 return Success(Val.countLeadingZeros(), E);
7670 }
7671
Richard Smith8889a3d2013-06-13 06:26:32 +00007672 case Builtin::BI__builtin_constant_p:
7673 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7674
Richard Smith80b3c8e2013-06-13 05:04:16 +00007675 case Builtin::BI__builtin_ctz:
7676 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007677 case Builtin::BI__builtin_ctzll:
7678 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007679 APSInt Val;
7680 if (!EvaluateInteger(E->getArg(0), Val, Info))
7681 return false;
7682 if (!Val)
7683 return Error(E);
7684
7685 return Success(Val.countTrailingZeros(), E);
7686 }
7687
Richard Smith8889a3d2013-06-13 06:26:32 +00007688 case Builtin::BI__builtin_eh_return_data_regno: {
7689 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7690 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7691 return Success(Operand, E);
7692 }
7693
7694 case Builtin::BI__builtin_expect:
7695 return Visit(E->getArg(0));
7696
7697 case Builtin::BI__builtin_ffs:
7698 case Builtin::BI__builtin_ffsl:
7699 case Builtin::BI__builtin_ffsll: {
7700 APSInt Val;
7701 if (!EvaluateInteger(E->getArg(0), Val, Info))
7702 return false;
7703
7704 unsigned N = Val.countTrailingZeros();
7705 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7706 }
7707
7708 case Builtin::BI__builtin_fpclassify: {
7709 APFloat Val(0.0);
7710 if (!EvaluateFloat(E->getArg(5), Val, Info))
7711 return false;
7712 unsigned Arg;
7713 switch (Val.getCategory()) {
7714 case APFloat::fcNaN: Arg = 0; break;
7715 case APFloat::fcInfinity: Arg = 1; break;
7716 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7717 case APFloat::fcZero: Arg = 4; break;
7718 }
7719 return Visit(E->getArg(Arg));
7720 }
7721
7722 case Builtin::BI__builtin_isinf_sign: {
7723 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007724 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007725 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7726 }
7727
Richard Smithea3019d2013-10-15 19:07:14 +00007728 case Builtin::BI__builtin_isinf: {
7729 APFloat Val(0.0);
7730 return EvaluateFloat(E->getArg(0), Val, Info) &&
7731 Success(Val.isInfinity() ? 1 : 0, E);
7732 }
7733
7734 case Builtin::BI__builtin_isfinite: {
7735 APFloat Val(0.0);
7736 return EvaluateFloat(E->getArg(0), Val, Info) &&
7737 Success(Val.isFinite() ? 1 : 0, E);
7738 }
7739
7740 case Builtin::BI__builtin_isnan: {
7741 APFloat Val(0.0);
7742 return EvaluateFloat(E->getArg(0), Val, Info) &&
7743 Success(Val.isNaN() ? 1 : 0, E);
7744 }
7745
7746 case Builtin::BI__builtin_isnormal: {
7747 APFloat Val(0.0);
7748 return EvaluateFloat(E->getArg(0), Val, Info) &&
7749 Success(Val.isNormal() ? 1 : 0, E);
7750 }
7751
Richard Smith8889a3d2013-06-13 06:26:32 +00007752 case Builtin::BI__builtin_parity:
7753 case Builtin::BI__builtin_parityl:
7754 case Builtin::BI__builtin_parityll: {
7755 APSInt Val;
7756 if (!EvaluateInteger(E->getArg(0), Val, Info))
7757 return false;
7758
7759 return Success(Val.countPopulation() % 2, E);
7760 }
7761
Richard Smith80b3c8e2013-06-13 05:04:16 +00007762 case Builtin::BI__builtin_popcount:
7763 case Builtin::BI__builtin_popcountl:
7764 case Builtin::BI__builtin_popcountll: {
7765 APSInt Val;
7766 if (!EvaluateInteger(E->getArg(0), Val, Info))
7767 return false;
7768
7769 return Success(Val.countPopulation(), E);
7770 }
7771
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007772 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007773 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007774 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007775 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007776 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007777 << /*isConstexpr*/0 << /*isConstructor*/0
7778 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007779 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007780 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007781 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007782 case Builtin::BI__builtin_strlen:
7783 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007784 // As an extension, we support __builtin_strlen() as a constant expression,
7785 // and support folding strlen() to a constant.
7786 LValue String;
7787 if (!EvaluatePointer(E->getArg(0), String, Info))
7788 return false;
7789
Richard Smith8110c9d2016-11-29 19:45:17 +00007790 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7791
Richard Smithe6c19f22013-11-15 02:10:04 +00007792 // Fast path: if it's a string literal, search the string value.
7793 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7794 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007795 // The string literal may have embedded null characters. Find the first
7796 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007797 StringRef Str = S->getBytes();
7798 int64_t Off = String.Offset.getQuantity();
7799 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007800 S->getCharByteWidth() == 1 &&
7801 // FIXME: Add fast-path for wchar_t too.
7802 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007803 Str = Str.substr(Off);
7804
7805 StringRef::size_type Pos = Str.find(0);
7806 if (Pos != StringRef::npos)
7807 Str = Str.substr(0, Pos);
7808
7809 return Success(Str.size(), E);
7810 }
7811
7812 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007813 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007814
7815 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007816 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7817 APValue Char;
7818 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7819 !Char.isInt())
7820 return false;
7821 if (!Char.getInt())
7822 return Success(Strlen, E);
7823 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7824 return false;
7825 }
7826 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007827
Richard Smithe151bab2016-11-11 23:43:35 +00007828 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007829 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007830 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007831 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007832 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007833 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007834 // A call to strlen is not a constant expression.
7835 if (Info.getLangOpts().CPlusPlus11)
7836 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7837 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007838 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007839 else
7840 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7841 // Fall through.
7842 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007843 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007844 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007845 case Builtin::BI__builtin_wcsncmp:
7846 case Builtin::BI__builtin_memcmp:
7847 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007848 LValue String1, String2;
7849 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7850 !EvaluatePointer(E->getArg(1), String2, Info))
7851 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007852
7853 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7854
Richard Smithe151bab2016-11-11 23:43:35 +00007855 uint64_t MaxLength = uint64_t(-1);
7856 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007857 BuiltinOp != Builtin::BIwcscmp &&
7858 BuiltinOp != Builtin::BI__builtin_strcmp &&
7859 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007860 APSInt N;
7861 if (!EvaluateInteger(E->getArg(2), N, Info))
7862 return false;
7863 MaxLength = N.getExtValue();
7864 }
7865 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007866 BuiltinOp != Builtin::BIwmemcmp &&
7867 BuiltinOp != Builtin::BI__builtin_memcmp &&
7868 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007869 for (; MaxLength; --MaxLength) {
7870 APValue Char1, Char2;
7871 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7872 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7873 !Char1.isInt() || !Char2.isInt())
7874 return false;
7875 if (Char1.getInt() != Char2.getInt())
7876 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7877 if (StopAtNull && !Char1.getInt())
7878 return Success(0, E);
7879 assert(!(StopAtNull && !Char2.getInt()));
7880 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7881 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7882 return false;
7883 }
7884 // We hit the strncmp / memcmp limit.
7885 return Success(0, E);
7886 }
7887
Richard Smith01ba47d2012-04-13 00:45:38 +00007888 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007889 case Builtin::BI__atomic_is_lock_free:
7890 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007891 APSInt SizeVal;
7892 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7893 return false;
7894
7895 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7896 // of two less than the maximum inline atomic width, we know it is
7897 // lock-free. If the size isn't a power of two, or greater than the
7898 // maximum alignment where we promote atomics, we know it is not lock-free
7899 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7900 // the answer can only be determined at runtime; for example, 16-byte
7901 // atomics have lock-free implementations on some, but not all,
7902 // x86-64 processors.
7903
7904 // Check power-of-two.
7905 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007906 if (Size.isPowerOfTwo()) {
7907 // Check against inlining width.
7908 unsigned InlineWidthBits =
7909 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7910 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7911 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7912 Size == CharUnits::One() ||
7913 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7914 Expr::NPC_NeverValueDependent))
7915 // OK, we will inline appropriately-aligned operations of this size,
7916 // and _Atomic(T) is appropriately-aligned.
7917 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007918
Richard Smith01ba47d2012-04-13 00:45:38 +00007919 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7920 castAs<PointerType>()->getPointeeType();
7921 if (!PointeeType->isIncompleteType() &&
7922 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7923 // OK, we will inline operations on this object.
7924 return Success(1, E);
7925 }
7926 }
7927 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007928
Richard Smith01ba47d2012-04-13 00:45:38 +00007929 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7930 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007931 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007932 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007933}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007934
Richard Smith8b3497e2011-10-31 01:37:14 +00007935static bool HasSameBase(const LValue &A, const LValue &B) {
7936 if (!A.getLValueBase())
7937 return !B.getLValueBase();
7938 if (!B.getLValueBase())
7939 return false;
7940
Richard Smithce40ad62011-11-12 22:28:03 +00007941 if (A.getLValueBase().getOpaqueValue() !=
7942 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007943 const Decl *ADecl = GetLValueBaseDecl(A);
7944 if (!ADecl)
7945 return false;
7946 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007947 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007948 return false;
7949 }
7950
7951 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007952 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007953}
7954
Richard Smithd20f1e62014-10-21 23:01:04 +00007955/// \brief Determine whether this is a pointer past the end of the complete
7956/// object referred to by the lvalue.
7957static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7958 const LValue &LV) {
7959 // A null pointer can be viewed as being "past the end" but we don't
7960 // choose to look at it that way here.
7961 if (!LV.getLValueBase())
7962 return false;
7963
7964 // If the designator is valid and refers to a subobject, we're not pointing
7965 // past the end.
7966 if (!LV.getLValueDesignator().Invalid &&
7967 !LV.getLValueDesignator().isOnePastTheEnd())
7968 return false;
7969
David Majnemerc378ca52015-08-29 08:32:55 +00007970 // A pointer to an incomplete type might be past-the-end if the type's size is
7971 // zero. We cannot tell because the type is incomplete.
7972 QualType Ty = getType(LV.getLValueBase());
7973 if (Ty->isIncompleteType())
7974 return true;
7975
Richard Smithd20f1e62014-10-21 23:01:04 +00007976 // We're a past-the-end pointer if we point to the byte after the object,
7977 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007978 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007979 return LV.getLValueOffset() == Size;
7980}
7981
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007982namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007983
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007984/// \brief Data recursive integer evaluator of certain binary operators.
7985///
7986/// We use a data recursive algorithm for binary operators so that we are able
7987/// to handle extreme cases of chained binary operators without causing stack
7988/// overflow.
7989class DataRecursiveIntBinOpEvaluator {
7990 struct EvalResult {
7991 APValue Val;
7992 bool Failed;
7993
7994 EvalResult() : Failed(false) { }
7995
7996 void swap(EvalResult &RHS) {
7997 Val.swap(RHS.Val);
7998 Failed = RHS.Failed;
7999 RHS.Failed = false;
8000 }
8001 };
8002
8003 struct Job {
8004 const Expr *E;
8005 EvalResult LHSResult; // meaningful only for binary operator expression.
8006 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008007
David Blaikie73726062015-08-12 23:09:24 +00008008 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008009 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008010
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008011 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008012 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008013 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008014
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008015 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008016 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008017 };
8018
8019 SmallVector<Job, 16> Queue;
8020
8021 IntExprEvaluator &IntEval;
8022 EvalInfo &Info;
8023 APValue &FinalResult;
8024
8025public:
8026 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8027 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8028
8029 /// \brief True if \param E is a binary operator that we are going to handle
8030 /// data recursively.
8031 /// We handle binary operators that are comma, logical, or that have operands
8032 /// with integral or enumeration type.
8033 static bool shouldEnqueue(const BinaryOperator *E) {
8034 return E->getOpcode() == BO_Comma ||
8035 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00008036 (E->isRValue() &&
8037 E->getType()->isIntegralOrEnumerationType() &&
8038 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008039 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008040 }
8041
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008042 bool Traverse(const BinaryOperator *E) {
8043 enqueue(E);
8044 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008045 while (!Queue.empty())
8046 process(PrevResult);
8047
8048 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008049
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008050 FinalResult.swap(PrevResult.Val);
8051 return true;
8052 }
8053
8054private:
8055 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8056 return IntEval.Success(Value, E, Result);
8057 }
8058 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8059 return IntEval.Success(Value, E, Result);
8060 }
8061 bool Error(const Expr *E) {
8062 return IntEval.Error(E);
8063 }
8064 bool Error(const Expr *E, diag::kind D) {
8065 return IntEval.Error(E, D);
8066 }
8067
8068 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8069 return Info.CCEDiag(E, D);
8070 }
8071
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008072 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8073 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008074 bool &SuppressRHSDiags);
8075
8076 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8077 const BinaryOperator *E, APValue &Result);
8078
8079 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8080 Result.Failed = !Evaluate(Result.Val, Info, E);
8081 if (Result.Failed)
8082 Result.Val = APValue();
8083 }
8084
Richard Trieuba4d0872012-03-21 23:30:30 +00008085 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008086
8087 void enqueue(const Expr *E) {
8088 E = E->IgnoreParens();
8089 Queue.resize(Queue.size()+1);
8090 Queue.back().E = E;
8091 Queue.back().Kind = Job::AnyExprKind;
8092 }
8093};
8094
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008095}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008096
8097bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008098 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008099 bool &SuppressRHSDiags) {
8100 if (E->getOpcode() == BO_Comma) {
8101 // Ignore LHS but note if we could not evaluate it.
8102 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008103 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008104 return true;
8105 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008106
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008107 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008108 bool LHSAsBool;
8109 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008110 // We were able to evaluate the LHS, see if we can get away with not
8111 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008112 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8113 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008114 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008115 }
8116 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008117 LHSResult.Failed = true;
8118
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008119 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008120 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008121 if (!Info.noteSideEffect())
8122 return false;
8123
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008124 // We can't evaluate the LHS; however, sometimes the result
8125 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8126 // Don't ignore RHS and suppress diagnostics from this arm.
8127 SuppressRHSDiags = true;
8128 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008129
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008130 return true;
8131 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008132
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008133 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8134 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008135
George Burgess IVa145e252016-05-25 22:38:36 +00008136 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008137 return false; // Ignore RHS;
8138
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008139 return true;
8140}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008141
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008142static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8143 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008144 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8145 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8146 // offsets.
8147 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8148 CharUnits &Offset = LVal.getLValueOffset();
8149 uint64_t Offset64 = Offset.getQuantity();
8150 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8151 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8152 : Offset64 + Index64);
8153}
8154
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008155bool DataRecursiveIntBinOpEvaluator::
8156 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8157 const BinaryOperator *E, APValue &Result) {
8158 if (E->getOpcode() == BO_Comma) {
8159 if (RHSResult.Failed)
8160 return false;
8161 Result = RHSResult.Val;
8162 return true;
8163 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008164
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008165 if (E->isLogicalOp()) {
8166 bool lhsResult, rhsResult;
8167 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8168 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Daniel Jasperffdee092017-05-02 19:21:42 +00008169
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008170 if (LHSIsOK) {
8171 if (RHSIsOK) {
8172 if (E->getOpcode() == BO_LOr)
8173 return Success(lhsResult || rhsResult, E, Result);
8174 else
8175 return Success(lhsResult && rhsResult, E, Result);
8176 }
8177 } else {
8178 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008179 // We can't evaluate the LHS; however, sometimes the result
8180 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8181 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008182 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008183 }
8184 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008185
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008186 return false;
8187 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008188
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008189 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8190 E->getRHS()->getType()->isIntegralOrEnumerationType());
Daniel Jasperffdee092017-05-02 19:21:42 +00008191
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008192 if (LHSResult.Failed || RHSResult.Failed)
8193 return false;
Daniel Jasperffdee092017-05-02 19:21:42 +00008194
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008195 const APValue &LHSVal = LHSResult.Val;
8196 const APValue &RHSVal = RHSResult.Val;
Daniel Jasperffdee092017-05-02 19:21:42 +00008197
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008198 // Handle cases like (unsigned long)&a + 4.
8199 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8200 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008201 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008202 return true;
8203 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008204
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008205 // Handle cases like 4 + (unsigned long)&a
8206 if (E->getOpcode() == BO_Add &&
8207 RHSVal.isLValue() && LHSVal.isInt()) {
8208 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008209 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008210 return true;
8211 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008212
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008213 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8214 // Handle (intptr_t)&&A - (intptr_t)&&B.
8215 if (!LHSVal.getLValueOffset().isZero() ||
8216 !RHSVal.getLValueOffset().isZero())
8217 return false;
8218 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8219 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8220 if (!LHSExpr || !RHSExpr)
8221 return false;
8222 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8223 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8224 if (!LHSAddrExpr || !RHSAddrExpr)
8225 return false;
8226 // Make sure both labels come from the same function.
8227 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8228 RHSAddrExpr->getLabel()->getDeclContext())
8229 return false;
8230 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8231 return true;
8232 }
Richard Smith43e77732013-05-07 04:50:00 +00008233
8234 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008235 if (!LHSVal.isInt() || !RHSVal.isInt())
8236 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008237
8238 // Set up the width and signedness manually, in case it can't be deduced
8239 // from the operation we're performing.
8240 // FIXME: Don't do this in the cases where we can deduce it.
8241 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8242 E->getType()->isUnsignedIntegerOrEnumerationType());
8243 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8244 RHSVal.getInt(), Value))
8245 return false;
8246 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008247}
8248
Richard Trieuba4d0872012-03-21 23:30:30 +00008249void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008250 Job &job = Queue.back();
Daniel Jasperffdee092017-05-02 19:21:42 +00008251
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008252 switch (job.Kind) {
8253 case Job::AnyExprKind: {
8254 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8255 if (shouldEnqueue(Bop)) {
8256 job.Kind = Job::BinOpKind;
8257 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008258 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008259 }
8260 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008261
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008262 EvaluateExpr(job.E, Result);
8263 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008264 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008265 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008266
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008267 case Job::BinOpKind: {
8268 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008269 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008270 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008271 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008272 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008273 }
8274 if (SuppressRHSDiags)
8275 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008276 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008277 job.Kind = Job::BinOpVisitedLHSKind;
8278 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008279 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008280 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008281
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008282 case Job::BinOpVisitedLHSKind: {
8283 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8284 EvalResult RHS;
8285 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008286 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008287 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008288 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008289 }
8290 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008291
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008292 llvm_unreachable("Invalid Job::Kind!");
8293}
8294
George Burgess IV8c892b52016-05-25 22:31:54 +00008295namespace {
8296/// Used when we determine that we should fail, but can keep evaluating prior to
8297/// noting that we had a failure.
8298class DelayedNoteFailureRAII {
8299 EvalInfo &Info;
8300 bool NoteFailure;
8301
8302public:
8303 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8304 : Info(Info), NoteFailure(NoteFailure) {}
8305 ~DelayedNoteFailureRAII() {
8306 if (NoteFailure) {
8307 bool ContinueAfterFailure = Info.noteFailure();
8308 (void)ContinueAfterFailure;
8309 assert(ContinueAfterFailure &&
8310 "Shouldn't have kept evaluating on failure.");
8311 }
8312 }
8313};
8314}
8315
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008316bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008317 // We don't call noteFailure immediately because the assignment happens after
8318 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008319 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008320 return Error(E);
8321
George Burgess IV8c892b52016-05-25 22:31:54 +00008322 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008323 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8324 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008325
Anders Carlssonacc79812008-11-16 07:17:21 +00008326 QualType LHSTy = E->getLHS()->getType();
8327 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008328
Chandler Carruthb29a7432014-10-11 11:03:30 +00008329 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008330 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008331 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008332 if (E->isAssignmentOp()) {
8333 LValue LV;
8334 EvaluateLValue(E->getLHS(), LV, Info);
8335 LHSOK = false;
8336 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008337 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8338 if (LHSOK) {
8339 LHS.makeComplexFloat();
8340 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8341 }
8342 } else {
8343 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8344 }
George Burgess IVa145e252016-05-25 22:38:36 +00008345 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008346 return false;
8347
Chandler Carruthb29a7432014-10-11 11:03:30 +00008348 if (E->getRHS()->getType()->isRealFloatingType()) {
8349 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8350 return false;
8351 RHS.makeComplexFloat();
8352 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8353 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008354 return false;
8355
8356 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008357 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008358 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008359 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008360 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8361
John McCalle3027922010-08-25 11:45:40 +00008362 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008363 return Success((CR_r == APFloat::cmpEqual &&
8364 CR_i == APFloat::cmpEqual), E);
8365 else {
John McCalle3027922010-08-25 11:45:40 +00008366 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008367 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008368 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008369 CR_r == APFloat::cmpLessThan ||
8370 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008371 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008372 CR_i == APFloat::cmpLessThan ||
8373 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008374 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008375 } else {
John McCalle3027922010-08-25 11:45:40 +00008376 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008377 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8378 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8379 else {
John McCalle3027922010-08-25 11:45:40 +00008380 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008381 "Invalid compex comparison.");
8382 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8383 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8384 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008385 }
8386 }
Mike Stump11289f42009-09-09 15:08:12 +00008387
Anders Carlssonacc79812008-11-16 07:17:21 +00008388 if (LHSTy->isRealFloatingType() &&
8389 RHSTy->isRealFloatingType()) {
8390 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008391
Richard Smith253c2a32012-01-27 01:14:48 +00008392 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008393 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008394 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008395
Richard Smith253c2a32012-01-27 01:14:48 +00008396 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008397 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008398
Anders Carlssonacc79812008-11-16 07:17:21 +00008399 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008400
Anders Carlssonacc79812008-11-16 07:17:21 +00008401 switch (E->getOpcode()) {
8402 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008403 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008404 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008405 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008406 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008407 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008408 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008409 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008410 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008411 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008412 E);
John McCalle3027922010-08-25 11:45:40 +00008413 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008414 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008415 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008416 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008417 || CR == APFloat::cmpLessThan
8418 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008419 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008420 }
Mike Stump11289f42009-09-09 15:08:12 +00008421
Eli Friedmana38da572009-04-28 19:17:36 +00008422 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008423 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008424 LValue LHSValue, RHSValue;
8425
8426 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008427 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008428 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008429
Richard Smith253c2a32012-01-27 01:14:48 +00008430 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008431 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008432
Richard Smith8b3497e2011-10-31 01:37:14 +00008433 // Reject differing bases from the normal codepath; we special-case
8434 // comparisons to null.
8435 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008436 if (E->getOpcode() == BO_Sub) {
8437 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008438 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008439 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008440 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008441 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008442 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008443 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008444 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8445 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8446 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008447 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008448 // Make sure both labels come from the same function.
8449 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8450 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008451 return Error(E);
8452 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008453 }
Richard Smith83c68212011-10-31 05:11:32 +00008454 // Inequalities and subtractions between unrelated pointers have
8455 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008456 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008457 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008458 // A constant address may compare equal to the address of a symbol.
8459 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008460 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008461 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8462 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008463 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008464 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008465 // distinct addresses. In clang, the result of such a comparison is
8466 // unspecified, so it is not a constant expression. However, we do know
8467 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008468 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8469 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008470 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008471 // We can't tell whether weak symbols will end up pointing to the same
8472 // object.
8473 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008474 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008475 // We can't compare the address of the start of one object with the
8476 // past-the-end address of another object, per C++ DR1652.
8477 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8478 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8479 (RHSValue.Base && RHSValue.Offset.isZero() &&
8480 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8481 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008482 // We can't tell whether an object is at the same address as another
8483 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008484 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8485 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008486 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008487 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008488 // (Note that clang defaults to -fmerge-all-constants, which can
8489 // lead to inconsistent results for comparisons involving the address
8490 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008491 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008492 }
Eli Friedman64004332009-03-23 04:38:34 +00008493
Richard Smith1b470412012-02-01 08:10:20 +00008494 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8495 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8496
Richard Smith84f6dcf2012-02-02 01:16:57 +00008497 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8498 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8499
John McCalle3027922010-08-25 11:45:40 +00008500 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008501 // C++11 [expr.add]p6:
8502 // Unless both pointers point to elements of the same array object, or
8503 // one past the last element of the array object, the behavior is
8504 // undefined.
8505 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8506 !AreElementsOfSameArray(getType(LHSValue.Base),
8507 LHSDesignator, RHSDesignator))
8508 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8509
Chris Lattner882bdf22010-04-20 17:13:14 +00008510 QualType Type = E->getLHS()->getType();
8511 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008512
Richard Smithd62306a2011-11-10 06:34:14 +00008513 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008514 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008515 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008516
Richard Smith84c6b3d2013-09-10 21:34:14 +00008517 // As an extension, a type may have zero size (empty struct or union in
8518 // C, array of zero length). Pointer subtraction in such cases has
8519 // undefined behavior, so is not constant.
8520 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008521 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008522 << ElementType;
8523 return false;
8524 }
8525
Richard Smith1b470412012-02-01 08:10:20 +00008526 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8527 // and produce incorrect results when it overflows. Such behavior
8528 // appears to be non-conforming, but is common, so perhaps we should
8529 // assume the standard intended for such cases to be undefined behavior
8530 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008531
Richard Smith1b470412012-02-01 08:10:20 +00008532 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8533 // overflow in the final conversion to ptrdiff_t.
8534 APSInt LHS(
8535 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8536 APSInt RHS(
8537 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8538 APSInt ElemSize(
8539 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8540 APSInt TrueResult = (LHS - RHS) / ElemSize;
8541 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8542
Richard Smith0c6124b2015-12-03 01:36:22 +00008543 if (Result.extend(65) != TrueResult &&
8544 !HandleOverflow(Info, E, TrueResult, E->getType()))
8545 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008546 return Success(Result, E);
8547 }
Richard Smithde21b242012-01-31 06:41:30 +00008548
8549 // C++11 [expr.rel]p3:
8550 // Pointers to void (after pointer conversions) can be compared, with a
8551 // result defined as follows: If both pointers represent the same
8552 // address or are both the null pointer value, the result is true if the
8553 // operator is <= or >= and false otherwise; otherwise the result is
8554 // unspecified.
8555 // We interpret this as applying to pointers to *cv* void.
8556 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008557 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008558 CCEDiag(E, diag::note_constexpr_void_comparison);
8559
Richard Smith84f6dcf2012-02-02 01:16:57 +00008560 // C++11 [expr.rel]p2:
8561 // - If two pointers point to non-static data members of the same object,
8562 // or to subobjects or array elements fo such members, recursively, the
8563 // pointer to the later declared member compares greater provided the
8564 // two members have the same access control and provided their class is
8565 // not a union.
8566 // [...]
8567 // - Otherwise pointer comparisons are unspecified.
8568 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8569 E->isRelationalOp()) {
8570 bool WasArrayIndex;
8571 unsigned Mismatch =
8572 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8573 RHSDesignator, WasArrayIndex);
8574 // At the point where the designators diverge, the comparison has a
8575 // specified value if:
8576 // - we are comparing array indices
8577 // - we are comparing fields of a union, or fields with the same access
8578 // Otherwise, the result is unspecified and thus the comparison is not a
8579 // constant expression.
8580 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8581 Mismatch < RHSDesignator.Entries.size()) {
8582 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8583 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8584 if (!LF && !RF)
8585 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8586 else if (!LF)
8587 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8588 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8589 << RF->getParent() << RF;
8590 else if (!RF)
8591 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8592 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8593 << LF->getParent() << LF;
8594 else if (!LF->getParent()->isUnion() &&
8595 LF->getAccess() != RF->getAccess())
8596 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8597 << LF << LF->getAccess() << RF << RF->getAccess()
8598 << LF->getParent();
8599 }
8600 }
8601
Eli Friedman6c31cb42012-04-16 04:30:08 +00008602 // The comparison here must be unsigned, and performed with the same
8603 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008604 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8605 uint64_t CompareLHS = LHSOffset.getQuantity();
8606 uint64_t CompareRHS = RHSOffset.getQuantity();
8607 assert(PtrSize <= 64 && "Unexpected pointer width");
8608 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8609 CompareLHS &= Mask;
8610 CompareRHS &= Mask;
8611
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008612 // If there is a base and this is a relational operator, we can only
8613 // compare pointers within the object in question; otherwise, the result
8614 // depends on where the object is located in memory.
8615 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8616 QualType BaseTy = getType(LHSValue.Base);
8617 if (BaseTy->isIncompleteType())
8618 return Error(E);
8619 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8620 uint64_t OffsetLimit = Size.getQuantity();
8621 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8622 return Error(E);
8623 }
8624
Richard Smith8b3497e2011-10-31 01:37:14 +00008625 switch (E->getOpcode()) {
8626 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008627 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8628 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8629 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8630 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8631 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8632 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008633 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008634 }
8635 }
Richard Smith7bb00672012-02-01 01:42:44 +00008636
8637 if (LHSTy->isMemberPointerType()) {
8638 assert(E->isEqualityOp() && "unexpected member pointer operation");
8639 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8640
8641 MemberPtr LHSValue, RHSValue;
8642
8643 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008644 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008645 return false;
8646
8647 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8648 return false;
8649
8650 // C++11 [expr.eq]p2:
8651 // If both operands are null, they compare equal. Otherwise if only one is
8652 // null, they compare unequal.
8653 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8654 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8655 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8656 }
8657
8658 // Otherwise if either is a pointer to a virtual member function, the
8659 // result is unspecified.
8660 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8661 if (MD->isVirtual())
8662 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8663 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8664 if (MD->isVirtual())
8665 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8666
8667 // Otherwise they compare equal if and only if they would refer to the
8668 // same member of the same most derived object or the same subobject if
8669 // they were dereferenced with a hypothetical object of the associated
8670 // class type.
8671 bool Equal = LHSValue == RHSValue;
8672 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8673 }
8674
Richard Smithab44d9b2012-02-14 22:35:28 +00008675 if (LHSTy->isNullPtrType()) {
8676 assert(E->isComparisonOp() && "unexpected nullptr operation");
8677 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8678 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8679 // are compared, the result is true of the operator is <=, >= or ==, and
8680 // false otherwise.
8681 BinaryOperator::Opcode Opcode = E->getOpcode();
8682 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8683 }
8684
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008685 assert((!LHSTy->isIntegralOrEnumerationType() ||
8686 !RHSTy->isIntegralOrEnumerationType()) &&
8687 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8688 // We can't continue from here for non-integral types.
8689 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008690}
8691
Peter Collingbournee190dee2011-03-11 19:24:49 +00008692/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8693/// a result as the expression's type.
8694bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8695 const UnaryExprOrTypeTraitExpr *E) {
8696 switch(E->getKind()) {
8697 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008698 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008699 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008700 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008701 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008702 }
Eli Friedman64004332009-03-23 04:38:34 +00008703
Peter Collingbournee190dee2011-03-11 19:24:49 +00008704 case UETT_VecStep: {
8705 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008706
Peter Collingbournee190dee2011-03-11 19:24:49 +00008707 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008708 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008709
Peter Collingbournee190dee2011-03-11 19:24:49 +00008710 // The vec_step built-in functions that take a 3-component
8711 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8712 if (n == 3)
8713 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008714
Peter Collingbournee190dee2011-03-11 19:24:49 +00008715 return Success(n, E);
8716 } else
8717 return Success(1, E);
8718 }
8719
8720 case UETT_SizeOf: {
8721 QualType SrcTy = E->getTypeOfArgument();
8722 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8723 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008724 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8725 SrcTy = Ref->getPointeeType();
8726
Richard Smithd62306a2011-11-10 06:34:14 +00008727 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008728 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008729 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008730 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008731 }
Alexey Bataev00396512015-07-02 03:40:19 +00008732 case UETT_OpenMPRequiredSimdAlign:
8733 assert(E->isArgumentType());
8734 return Success(
8735 Info.Ctx.toCharUnitsFromBits(
8736 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8737 .getQuantity(),
8738 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008739 }
8740
8741 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008742}
8743
Peter Collingbournee9200682011-05-13 03:29:01 +00008744bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008745 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008746 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008747 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008748 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008749 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008750 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008751 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008752 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008753 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008754 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008755 APSInt IdxResult;
8756 if (!EvaluateInteger(Idx, IdxResult, Info))
8757 return false;
8758 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8759 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008760 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008761 CurrentType = AT->getElementType();
8762 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8763 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008764 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008765 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008766
James Y Knight7281c352015-12-29 22:31:18 +00008767 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008768 FieldDecl *MemberDecl = ON.getField();
8769 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008770 if (!RT)
8771 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008772 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008773 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008774 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008775 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008776 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008777 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008778 CurrentType = MemberDecl->getType().getNonReferenceType();
8779 break;
8780 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008781
James Y Knight7281c352015-12-29 22:31:18 +00008782 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008783 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008784
James Y Knight7281c352015-12-29 22:31:18 +00008785 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008786 CXXBaseSpecifier *BaseSpec = ON.getBase();
8787 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008788 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008789
8790 // Find the layout of the class whose base we are looking into.
8791 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008792 if (!RT)
8793 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008794 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008795 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008796 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8797
8798 // Find the base class itself.
8799 CurrentType = BaseSpec->getType();
8800 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8801 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008802 return Error(OOE);
Daniel Jasperffdee092017-05-02 19:21:42 +00008803
Douglas Gregord1702062010-04-29 00:18:15 +00008804 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008805 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008806 break;
8807 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008808 }
8809 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008810 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008811}
8812
Chris Lattnere13042c2008-07-11 19:10:17 +00008813bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008814 switch (E->getOpcode()) {
8815 default:
8816 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8817 // See C99 6.6p3.
8818 return Error(E);
8819 case UO_Extension:
8820 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8821 // If so, we could clear the diagnostic ID.
8822 return Visit(E->getSubExpr());
8823 case UO_Plus:
8824 // The result is just the value.
8825 return Visit(E->getSubExpr());
8826 case UO_Minus: {
8827 if (!Visit(E->getSubExpr()))
8828 return false;
8829 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008830 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008831 if (Value.isSigned() && Value.isMinSignedValue() &&
8832 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8833 E->getType()))
8834 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008835 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008836 }
8837 case UO_Not: {
8838 if (!Visit(E->getSubExpr()))
8839 return false;
8840 if (!Result.isInt()) return Error(E);
8841 return Success(~Result.getInt(), E);
8842 }
8843 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008844 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008845 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008846 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008847 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008848 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008849 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008850}
Mike Stump11289f42009-09-09 15:08:12 +00008851
Chris Lattner477c4be2008-07-12 01:15:53 +00008852/// HandleCast - This is used to evaluate implicit or explicit casts where the
8853/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008854bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8855 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008856 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008857 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008858
Eli Friedmanc757de22011-03-25 00:43:55 +00008859 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008860 case CK_BaseToDerived:
8861 case CK_DerivedToBase:
8862 case CK_UncheckedDerivedToBase:
8863 case CK_Dynamic:
8864 case CK_ToUnion:
8865 case CK_ArrayToPointerDecay:
8866 case CK_FunctionToPointerDecay:
8867 case CK_NullToPointer:
8868 case CK_NullToMemberPointer:
8869 case CK_BaseToDerivedMemberPointer:
8870 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008871 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008872 case CK_ConstructorConversion:
8873 case CK_IntegralToPointer:
8874 case CK_ToVoid:
8875 case CK_VectorSplat:
8876 case CK_IntegralToFloating:
8877 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008878 case CK_CPointerToObjCPointerCast:
8879 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008880 case CK_AnyPointerToBlockPointerCast:
8881 case CK_ObjCObjectLValueCast:
8882 case CK_FloatingRealToComplex:
8883 case CK_FloatingComplexToReal:
8884 case CK_FloatingComplexCast:
8885 case CK_FloatingComplexToIntegralComplex:
8886 case CK_IntegralRealToComplex:
8887 case CK_IntegralComplexCast:
8888 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008889 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008890 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008891 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008892 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008893 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008894 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008895 llvm_unreachable("invalid cast kind for integral value");
8896
Eli Friedman9faf2f92011-03-25 19:07:11 +00008897 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008898 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008899 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008900 case CK_ARCProduceObject:
8901 case CK_ARCConsumeObject:
8902 case CK_ARCReclaimReturnedObject:
8903 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008904 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008905 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008906
Richard Smith4ef685b2012-01-17 21:17:26 +00008907 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008908 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008909 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008910 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008911 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008912
8913 case CK_MemberPointerToBoolean:
8914 case CK_PointerToBoolean:
8915 case CK_IntegralToBoolean:
8916 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008917 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008918 case CK_FloatingComplexToBoolean:
8919 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008920 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008921 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008922 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008923 uint64_t IntResult = BoolResult;
8924 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8925 IntResult = (uint64_t)-1;
8926 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008927 }
8928
Eli Friedmanc757de22011-03-25 00:43:55 +00008929 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008930 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008931 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008932
Eli Friedman742421e2009-02-20 01:15:07 +00008933 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008934 // Allow casts of address-of-label differences if they are no-ops
8935 // or narrowing. (The narrowing case isn't actually guaranteed to
8936 // be constant-evaluatable except in some narrow cases which are hard
8937 // to detect here. We let it through on the assumption the user knows
8938 // what they are doing.)
8939 if (Result.isAddrLabelDiff())
8940 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008941 // Only allow casts of lvalues if they are lossless.
8942 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8943 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008944
Richard Smith911e1422012-01-30 22:27:01 +00008945 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8946 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008947 }
Mike Stump11289f42009-09-09 15:08:12 +00008948
Eli Friedmanc757de22011-03-25 00:43:55 +00008949 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008950 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8951
John McCall45d55e42010-05-07 21:00:08 +00008952 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008953 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008954 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008955
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008956 if (LV.getLValueBase()) {
8957 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008958 // FIXME: Allow a larger integer size than the pointer size, and allow
8959 // narrowing back down to pointer width in subsequent integral casts.
8960 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008961 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008962 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008963
Richard Smithcf74da72011-11-16 07:18:12 +00008964 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008965 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008966 return true;
8967 }
8968
Yaxun Liu402804b2016-12-15 08:09:08 +00008969 uint64_t V;
8970 if (LV.isNullPointer())
8971 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8972 else
8973 V = LV.getLValueOffset().getQuantity();
8974
8975 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008976 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008977 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008978
Eli Friedmanc757de22011-03-25 00:43:55 +00008979 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008980 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008981 if (!EvaluateComplex(SubExpr, C, Info))
8982 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008983 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008984 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008985
Eli Friedmanc757de22011-03-25 00:43:55 +00008986 case CK_FloatingToIntegral: {
8987 APFloat F(0.0);
8988 if (!EvaluateFloat(SubExpr, F, Info))
8989 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008990
Richard Smith357362d2011-12-13 06:39:58 +00008991 APSInt Value;
8992 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8993 return false;
8994 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008995 }
8996 }
Mike Stump11289f42009-09-09 15:08:12 +00008997
Eli Friedmanc757de22011-03-25 00:43:55 +00008998 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008999}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009000
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009001bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9002 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009003 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009004 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9005 return false;
9006 if (!LV.isComplexInt())
9007 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009008 return Success(LV.getComplexIntReal(), E);
9009 }
9010
9011 return Visit(E->getSubExpr());
9012}
9013
Eli Friedman4e7a2412009-02-27 04:45:43 +00009014bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009015 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009016 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009017 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9018 return false;
9019 if (!LV.isComplexInt())
9020 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009021 return Success(LV.getComplexIntImag(), E);
9022 }
9023
Richard Smith4a678122011-10-24 18:44:57 +00009024 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009025 return Success(0, E);
9026}
9027
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009028bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9029 return Success(E->getPackLength(), E);
9030}
9031
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009032bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9033 return Success(E->getValue(), E);
9034}
9035
Chris Lattner05706e882008-07-11 18:11:29 +00009036//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009037// Float Evaluation
9038//===----------------------------------------------------------------------===//
9039
9040namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009041class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009042 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009043 APFloat &Result;
9044public:
9045 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009046 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009047
Richard Smith2e312c82012-03-03 22:46:17 +00009048 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009049 Result = V.getFloat();
9050 return true;
9051 }
Eli Friedman24c01542008-08-22 00:06:13 +00009052
Richard Smithfddd3842011-12-30 21:15:51 +00009053 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009054 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9055 return true;
9056 }
9057
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009058 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009059
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009060 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009061 bool VisitBinaryOperator(const BinaryOperator *E);
9062 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009063 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009064
John McCallb1fb0d32010-05-07 22:08:54 +00009065 bool VisitUnaryReal(const UnaryOperator *E);
9066 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009067
Richard Smithfddd3842011-12-30 21:15:51 +00009068 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009069};
9070} // end anonymous namespace
9071
9072static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009073 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009074 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009075}
9076
Jay Foad39c79802011-01-12 09:06:06 +00009077static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009078 QualType ResultTy,
9079 const Expr *Arg,
9080 bool SNaN,
9081 llvm::APFloat &Result) {
9082 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9083 if (!S) return false;
9084
9085 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9086
9087 llvm::APInt fill;
9088
9089 // Treat empty strings as if they were zero.
9090 if (S->getString().empty())
9091 fill = llvm::APInt(32, 0);
9092 else if (S->getString().getAsInteger(0, fill))
9093 return false;
9094
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009095 if (Context.getTargetInfo().isNan2008()) {
9096 if (SNaN)
9097 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9098 else
9099 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9100 } else {
9101 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9102 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9103 // a different encoding to what became a standard in 2008, and for pre-
9104 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9105 // sNaN. This is now known as "legacy NaN" encoding.
9106 if (SNaN)
9107 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9108 else
9109 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9110 }
9111
John McCall16291492010-02-28 13:00:19 +00009112 return true;
9113}
9114
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009115bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009116 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009117 default:
9118 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9119
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009120 case Builtin::BI__builtin_huge_val:
9121 case Builtin::BI__builtin_huge_valf:
9122 case Builtin::BI__builtin_huge_vall:
9123 case Builtin::BI__builtin_inf:
9124 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009125 case Builtin::BI__builtin_infl: {
9126 const llvm::fltSemantics &Sem =
9127 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009128 Result = llvm::APFloat::getInf(Sem);
9129 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009130 }
Mike Stump11289f42009-09-09 15:08:12 +00009131
John McCall16291492010-02-28 13:00:19 +00009132 case Builtin::BI__builtin_nans:
9133 case Builtin::BI__builtin_nansf:
9134 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009135 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9136 true, Result))
9137 return Error(E);
9138 return true;
John McCall16291492010-02-28 13:00:19 +00009139
Chris Lattner0b7282e2008-10-06 06:31:58 +00009140 case Builtin::BI__builtin_nan:
9141 case Builtin::BI__builtin_nanf:
9142 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00009143 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009144 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009145 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9146 false, Result))
9147 return Error(E);
9148 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009149
9150 case Builtin::BI__builtin_fabs:
9151 case Builtin::BI__builtin_fabsf:
9152 case Builtin::BI__builtin_fabsl:
9153 if (!EvaluateFloat(E->getArg(0), Result, Info))
9154 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009155
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009156 if (Result.isNegative())
9157 Result.changeSign();
9158 return true;
9159
Richard Smith8889a3d2013-06-13 06:26:32 +00009160 // FIXME: Builtin::BI__builtin_powi
9161 // FIXME: Builtin::BI__builtin_powif
9162 // FIXME: Builtin::BI__builtin_powil
9163
Mike Stump11289f42009-09-09 15:08:12 +00009164 case Builtin::BI__builtin_copysign:
9165 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009166 case Builtin::BI__builtin_copysignl: {
9167 APFloat RHS(0.);
9168 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9169 !EvaluateFloat(E->getArg(1), RHS, Info))
9170 return false;
9171 Result.copySign(RHS);
9172 return true;
9173 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009174 }
9175}
9176
John McCallb1fb0d32010-05-07 22:08:54 +00009177bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009178 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9179 ComplexValue CV;
9180 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9181 return false;
9182 Result = CV.FloatReal;
9183 return true;
9184 }
9185
9186 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009187}
9188
9189bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009190 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9191 ComplexValue CV;
9192 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9193 return false;
9194 Result = CV.FloatImag;
9195 return true;
9196 }
9197
Richard Smith4a678122011-10-24 18:44:57 +00009198 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009199 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9200 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009201 return true;
9202}
9203
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009204bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009205 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009206 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009207 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009208 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009209 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009210 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9211 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009212 Result.changeSign();
9213 return true;
9214 }
9215}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009216
Eli Friedman24c01542008-08-22 00:06:13 +00009217bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009218 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9219 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009220
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009221 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009222 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009223 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009224 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009225 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9226 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009227}
9228
9229bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9230 Result = E->getValue();
9231 return true;
9232}
9233
Peter Collingbournee9200682011-05-13 03:29:01 +00009234bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9235 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009236
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009237 switch (E->getCastKind()) {
9238 default:
Richard Smith11562c52011-10-28 17:51:58 +00009239 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009240
9241 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009242 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009243 return EvaluateInteger(SubExpr, IntResult, Info) &&
9244 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9245 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009246 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009247
9248 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009249 if (!Visit(SubExpr))
9250 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009251 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9252 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009253 }
John McCalld7646252010-11-14 08:17:51 +00009254
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009255 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009256 ComplexValue V;
9257 if (!EvaluateComplex(SubExpr, V, Info))
9258 return false;
9259 Result = V.getComplexFloatReal();
9260 return true;
9261 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009262 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009263}
9264
Eli Friedman24c01542008-08-22 00:06:13 +00009265//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009266// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009267//===----------------------------------------------------------------------===//
9268
9269namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009270class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009271 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009272 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009273
Anders Carlsson537969c2008-11-16 20:27:53 +00009274public:
John McCall93d91dc2010-05-07 17:22:02 +00009275 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009276 : ExprEvaluatorBaseTy(info), Result(Result) {}
9277
Richard Smith2e312c82012-03-03 22:46:17 +00009278 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009279 Result.setFrom(V);
9280 return true;
9281 }
Mike Stump11289f42009-09-09 15:08:12 +00009282
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009283 bool ZeroInitialization(const Expr *E);
9284
Anders Carlsson537969c2008-11-16 20:27:53 +00009285 //===--------------------------------------------------------------------===//
9286 // Visitor Methods
9287 //===--------------------------------------------------------------------===//
9288
Peter Collingbournee9200682011-05-13 03:29:01 +00009289 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009290 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009291 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009292 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009293 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009294};
9295} // end anonymous namespace
9296
John McCall93d91dc2010-05-07 17:22:02 +00009297static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9298 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009299 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009300 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009301}
9302
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009303bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009304 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009305 if (ElemTy->isRealFloatingType()) {
9306 Result.makeComplexFloat();
9307 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9308 Result.FloatReal = Zero;
9309 Result.FloatImag = Zero;
9310 } else {
9311 Result.makeComplexInt();
9312 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9313 Result.IntReal = Zero;
9314 Result.IntImag = Zero;
9315 }
9316 return true;
9317}
9318
Peter Collingbournee9200682011-05-13 03:29:01 +00009319bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9320 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009321
9322 if (SubExpr->getType()->isRealFloatingType()) {
9323 Result.makeComplexFloat();
9324 APFloat &Imag = Result.FloatImag;
9325 if (!EvaluateFloat(SubExpr, Imag, Info))
9326 return false;
9327
9328 Result.FloatReal = APFloat(Imag.getSemantics());
9329 return true;
9330 } else {
9331 assert(SubExpr->getType()->isIntegerType() &&
9332 "Unexpected imaginary literal.");
9333
9334 Result.makeComplexInt();
9335 APSInt &Imag = Result.IntImag;
9336 if (!EvaluateInteger(SubExpr, Imag, Info))
9337 return false;
9338
9339 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9340 return true;
9341 }
9342}
9343
Peter Collingbournee9200682011-05-13 03:29:01 +00009344bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009345
John McCallfcef3cf2010-12-14 17:51:41 +00009346 switch (E->getCastKind()) {
9347 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009348 case CK_BaseToDerived:
9349 case CK_DerivedToBase:
9350 case CK_UncheckedDerivedToBase:
9351 case CK_Dynamic:
9352 case CK_ToUnion:
9353 case CK_ArrayToPointerDecay:
9354 case CK_FunctionToPointerDecay:
9355 case CK_NullToPointer:
9356 case CK_NullToMemberPointer:
9357 case CK_BaseToDerivedMemberPointer:
9358 case CK_DerivedToBaseMemberPointer:
9359 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009360 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009361 case CK_ConstructorConversion:
9362 case CK_IntegralToPointer:
9363 case CK_PointerToIntegral:
9364 case CK_PointerToBoolean:
9365 case CK_ToVoid:
9366 case CK_VectorSplat:
9367 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009368 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009369 case CK_IntegralToBoolean:
9370 case CK_IntegralToFloating:
9371 case CK_FloatingToIntegral:
9372 case CK_FloatingToBoolean:
9373 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009374 case CK_CPointerToObjCPointerCast:
9375 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009376 case CK_AnyPointerToBlockPointerCast:
9377 case CK_ObjCObjectLValueCast:
9378 case CK_FloatingComplexToReal:
9379 case CK_FloatingComplexToBoolean:
9380 case CK_IntegralComplexToReal:
9381 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009382 case CK_ARCProduceObject:
9383 case CK_ARCConsumeObject:
9384 case CK_ARCReclaimReturnedObject:
9385 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009386 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009387 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009388 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009389 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009390 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009391 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009392 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009393 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009394
John McCallfcef3cf2010-12-14 17:51:41 +00009395 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009396 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009397 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009398 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009399
9400 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009401 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009402 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009403 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009404
9405 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009406 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009407 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009408 return false;
9409
John McCallfcef3cf2010-12-14 17:51:41 +00009410 Result.makeComplexFloat();
9411 Result.FloatImag = APFloat(Real.getSemantics());
9412 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009413 }
9414
John McCallfcef3cf2010-12-14 17:51:41 +00009415 case CK_FloatingComplexCast: {
9416 if (!Visit(E->getSubExpr()))
9417 return false;
9418
9419 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9420 QualType From
9421 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9422
Richard Smith357362d2011-12-13 06:39:58 +00009423 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9424 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009425 }
9426
9427 case CK_FloatingComplexToIntegralComplex: {
9428 if (!Visit(E->getSubExpr()))
9429 return false;
9430
9431 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9432 QualType From
9433 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9434 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009435 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9436 To, Result.IntReal) &&
9437 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9438 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009439 }
9440
9441 case CK_IntegralRealToComplex: {
9442 APSInt &Real = Result.IntReal;
9443 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9444 return false;
9445
9446 Result.makeComplexInt();
9447 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9448 return true;
9449 }
9450
9451 case CK_IntegralComplexCast: {
9452 if (!Visit(E->getSubExpr()))
9453 return false;
9454
9455 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9456 QualType From
9457 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9458
Richard Smith911e1422012-01-30 22:27:01 +00009459 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9460 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009461 return true;
9462 }
9463
9464 case CK_IntegralComplexToFloatingComplex: {
9465 if (!Visit(E->getSubExpr()))
9466 return false;
9467
Ted Kremenek28831752012-08-23 20:46:57 +00009468 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009469 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009470 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009471 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009472 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9473 To, Result.FloatReal) &&
9474 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9475 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009476 }
9477 }
9478
9479 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009480}
9481
John McCall93d91dc2010-05-07 17:22:02 +00009482bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009483 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009484 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9485
Chandler Carrutha216cad2014-10-11 00:57:18 +00009486 // Track whether the LHS or RHS is real at the type system level. When this is
9487 // the case we can simplify our evaluation strategy.
9488 bool LHSReal = false, RHSReal = false;
9489
9490 bool LHSOK;
9491 if (E->getLHS()->getType()->isRealFloatingType()) {
9492 LHSReal = true;
9493 APFloat &Real = Result.FloatReal;
9494 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9495 if (LHSOK) {
9496 Result.makeComplexFloat();
9497 Result.FloatImag = APFloat(Real.getSemantics());
9498 }
9499 } else {
9500 LHSOK = Visit(E->getLHS());
9501 }
George Burgess IVa145e252016-05-25 22:38:36 +00009502 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009503 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009504
John McCall93d91dc2010-05-07 17:22:02 +00009505 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009506 if (E->getRHS()->getType()->isRealFloatingType()) {
9507 RHSReal = true;
9508 APFloat &Real = RHS.FloatReal;
9509 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9510 return false;
9511 RHS.makeComplexFloat();
9512 RHS.FloatImag = APFloat(Real.getSemantics());
9513 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009514 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009515
Chandler Carrutha216cad2014-10-11 00:57:18 +00009516 assert(!(LHSReal && RHSReal) &&
9517 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009518 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009519 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009520 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009521 if (Result.isComplexFloat()) {
9522 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9523 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009524 if (LHSReal)
9525 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9526 else if (!RHSReal)
9527 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9528 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009529 } else {
9530 Result.getComplexIntReal() += RHS.getComplexIntReal();
9531 Result.getComplexIntImag() += RHS.getComplexIntImag();
9532 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009533 break;
John McCalle3027922010-08-25 11:45:40 +00009534 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009535 if (Result.isComplexFloat()) {
9536 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9537 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009538 if (LHSReal) {
9539 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9540 Result.getComplexFloatImag().changeSign();
9541 } else if (!RHSReal) {
9542 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9543 APFloat::rmNearestTiesToEven);
9544 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009545 } else {
9546 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9547 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9548 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009549 break;
John McCalle3027922010-08-25 11:45:40 +00009550 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009551 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009552 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009553 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009554 // following naming scheme:
9555 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009556 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009557 APFloat &A = LHS.getComplexFloatReal();
9558 APFloat &B = LHS.getComplexFloatImag();
9559 APFloat &C = RHS.getComplexFloatReal();
9560 APFloat &D = RHS.getComplexFloatImag();
9561 APFloat &ResR = Result.getComplexFloatReal();
9562 APFloat &ResI = Result.getComplexFloatImag();
9563 if (LHSReal) {
9564 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9565 ResR = A * C;
9566 ResI = A * D;
9567 } else if (RHSReal) {
9568 ResR = C * A;
9569 ResI = C * B;
9570 } else {
9571 // In the fully general case, we need to handle NaNs and infinities
9572 // robustly.
9573 APFloat AC = A * C;
9574 APFloat BD = B * D;
9575 APFloat AD = A * D;
9576 APFloat BC = B * C;
9577 ResR = AC - BD;
9578 ResI = AD + BC;
9579 if (ResR.isNaN() && ResI.isNaN()) {
9580 bool Recalc = false;
9581 if (A.isInfinity() || B.isInfinity()) {
9582 A = APFloat::copySign(
9583 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9584 B = APFloat::copySign(
9585 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9586 if (C.isNaN())
9587 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9588 if (D.isNaN())
9589 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9590 Recalc = true;
9591 }
9592 if (C.isInfinity() || D.isInfinity()) {
9593 C = APFloat::copySign(
9594 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9595 D = APFloat::copySign(
9596 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9597 if (A.isNaN())
9598 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9599 if (B.isNaN())
9600 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9601 Recalc = true;
9602 }
9603 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9604 AD.isInfinity() || BC.isInfinity())) {
9605 if (A.isNaN())
9606 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9607 if (B.isNaN())
9608 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9609 if (C.isNaN())
9610 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9611 if (D.isNaN())
9612 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9613 Recalc = true;
9614 }
9615 if (Recalc) {
9616 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9617 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9618 }
9619 }
9620 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009621 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009622 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009623 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009624 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9625 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009626 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009627 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9628 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9629 }
9630 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009631 case BO_Div:
9632 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009633 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009634 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009635 // following naming scheme:
9636 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009637 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009638 APFloat &A = LHS.getComplexFloatReal();
9639 APFloat &B = LHS.getComplexFloatImag();
9640 APFloat &C = RHS.getComplexFloatReal();
9641 APFloat &D = RHS.getComplexFloatImag();
9642 APFloat &ResR = Result.getComplexFloatReal();
9643 APFloat &ResI = Result.getComplexFloatImag();
9644 if (RHSReal) {
9645 ResR = A / C;
9646 ResI = B / C;
9647 } else {
9648 if (LHSReal) {
9649 // No real optimizations we can do here, stub out with zero.
9650 B = APFloat::getZero(A.getSemantics());
9651 }
9652 int DenomLogB = 0;
9653 APFloat MaxCD = maxnum(abs(C), abs(D));
9654 if (MaxCD.isFinite()) {
9655 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009656 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9657 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009658 }
9659 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009660 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9661 APFloat::rmNearestTiesToEven);
9662 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9663 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009664 if (ResR.isNaN() && ResI.isNaN()) {
9665 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9666 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9667 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9668 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9669 D.isFinite()) {
9670 A = APFloat::copySign(
9671 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9672 B = APFloat::copySign(
9673 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9674 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9675 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9676 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9677 C = APFloat::copySign(
9678 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9679 D = APFloat::copySign(
9680 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9681 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9682 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9683 }
9684 }
9685 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009686 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009687 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9688 return Error(E, diag::note_expr_divide_by_zero);
9689
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009690 ComplexValue LHS = Result;
9691 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9692 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9693 Result.getComplexIntReal() =
9694 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9695 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9696 Result.getComplexIntImag() =
9697 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9698 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9699 }
9700 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009701 }
9702
John McCall93d91dc2010-05-07 17:22:02 +00009703 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009704}
9705
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009706bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9707 // Get the operand value into 'Result'.
9708 if (!Visit(E->getSubExpr()))
9709 return false;
9710
9711 switch (E->getOpcode()) {
9712 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009713 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009714 case UO_Extension:
9715 return true;
9716 case UO_Plus:
9717 // The result is always just the subexpr.
9718 return true;
9719 case UO_Minus:
9720 if (Result.isComplexFloat()) {
9721 Result.getComplexFloatReal().changeSign();
9722 Result.getComplexFloatImag().changeSign();
9723 }
9724 else {
9725 Result.getComplexIntReal() = -Result.getComplexIntReal();
9726 Result.getComplexIntImag() = -Result.getComplexIntImag();
9727 }
9728 return true;
9729 case UO_Not:
9730 if (Result.isComplexFloat())
9731 Result.getComplexFloatImag().changeSign();
9732 else
9733 Result.getComplexIntImag() = -Result.getComplexIntImag();
9734 return true;
9735 }
9736}
9737
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009738bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9739 if (E->getNumInits() == 2) {
9740 if (E->getType()->isComplexType()) {
9741 Result.makeComplexFloat();
9742 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9743 return false;
9744 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9745 return false;
9746 } else {
9747 Result.makeComplexInt();
9748 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9749 return false;
9750 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9751 return false;
9752 }
9753 return true;
9754 }
9755 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9756}
9757
Anders Carlsson537969c2008-11-16 20:27:53 +00009758//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009759// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9760// implicit conversion.
9761//===----------------------------------------------------------------------===//
9762
9763namespace {
9764class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009765 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009766 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +00009767 APValue &Result;
9768public:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009769 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9770 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +00009771
9772 bool Success(const APValue &V, const Expr *E) {
9773 Result = V;
9774 return true;
9775 }
9776
9777 bool ZeroInitialization(const Expr *E) {
9778 ImplicitValueInitExpr VIE(
9779 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009780 // For atomic-qualified class (and array) types in C++, initialize the
9781 // _Atomic-wrapped subobject directly, in-place.
9782 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9783 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +00009784 }
9785
9786 bool VisitCastExpr(const CastExpr *E) {
9787 switch (E->getCastKind()) {
9788 default:
9789 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9790 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009791 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9792 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +00009793 }
9794 }
9795};
9796} // end anonymous namespace
9797
Richard Smith64cb9ca2017-02-22 22:09:50 +00009798static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9799 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +00009800 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009801 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +00009802}
9803
9804//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009805// Void expression evaluation, primarily for a cast to void on the LHS of a
9806// comma operator
9807//===----------------------------------------------------------------------===//
9808
9809namespace {
9810class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009811 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009812public:
9813 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9814
Richard Smith2e312c82012-03-03 22:46:17 +00009815 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009816
Richard Smith7cd577b2017-08-17 19:35:50 +00009817 bool ZeroInitialization(const Expr *E) { return true; }
9818
Richard Smith42d3af92011-12-07 00:43:50 +00009819 bool VisitCastExpr(const CastExpr *E) {
9820 switch (E->getCastKind()) {
9821 default:
9822 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9823 case CK_ToVoid:
9824 VisitIgnoredValue(E->getSubExpr());
9825 return true;
9826 }
9827 }
Hal Finkela8443c32014-07-17 14:49:58 +00009828
9829 bool VisitCallExpr(const CallExpr *E) {
9830 switch (E->getBuiltinCallee()) {
9831 default:
9832 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9833 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009834 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009835 // The argument is not evaluated!
9836 return true;
9837 }
9838 }
Richard Smith42d3af92011-12-07 00:43:50 +00009839};
9840} // end anonymous namespace
9841
9842static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9843 assert(E->isRValue() && E->getType()->isVoidType());
9844 return VoidExprEvaluator(Info).Visit(E);
9845}
9846
9847//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009848// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009849//===----------------------------------------------------------------------===//
9850
Richard Smith2e312c82012-03-03 22:46:17 +00009851static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009852 // In C, function designators are not lvalues, but we evaluate them as if they
9853 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009854 QualType T = E->getType();
9855 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009856 LValue LV;
9857 if (!EvaluateLValue(E, LV, Info))
9858 return false;
9859 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009860 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009861 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009862 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009863 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009864 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009865 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009866 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009867 LValue LV;
9868 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009869 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009870 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009871 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009872 llvm::APFloat F(0.0);
9873 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009874 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009875 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009876 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009877 ComplexValue C;
9878 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009879 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009880 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009881 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009882 MemberPtr P;
9883 if (!EvaluateMemberPointer(E, P, Info))
9884 return false;
9885 P.moveInto(Result);
9886 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009887 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009888 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009889 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009890 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9891 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009892 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009893 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009894 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009895 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009896 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009897 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9898 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009899 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009900 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009901 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009902 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009903 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009904 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009905 if (!EvaluateVoid(E, Info))
9906 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009907 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009908 QualType Unqual = T.getAtomicUnqualifiedType();
9909 if (Unqual->isArrayType() || Unqual->isRecordType()) {
9910 LValue LV;
9911 LV.set(E, Info.CurrentCall->Index);
9912 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9913 if (!EvaluateAtomic(E, &LV, Value, Info))
9914 return false;
9915 } else {
9916 if (!EvaluateAtomic(E, nullptr, Result, Info))
9917 return false;
9918 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009919 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009920 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009921 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009922 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009923 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009924 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009925 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009926
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009927 return true;
9928}
9929
Richard Smithb228a862012-02-15 02:18:13 +00009930/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9931/// cases, the in-place evaluation is essential, since later initializers for
9932/// an object can indirectly refer to subobjects which were initialized earlier.
9933static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009934 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009935 assert(!E->isValueDependent());
9936
Richard Smith7525ff62013-05-09 07:14:00 +00009937 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009938 return false;
9939
9940 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009941 // Evaluate arrays and record types in-place, so that later initializers can
9942 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +00009943 QualType T = E->getType();
9944 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +00009945 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00009946 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +00009947 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00009948 else if (T->isAtomicType()) {
9949 QualType Unqual = T.getAtomicUnqualifiedType();
9950 if (Unqual->isArrayType() || Unqual->isRecordType())
9951 return EvaluateAtomic(E, &This, Result, Info);
9952 }
Richard Smithed5165f2011-11-04 05:33:44 +00009953 }
9954
9955 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009956 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009957}
9958
Richard Smithf57d8cb2011-12-09 22:58:01 +00009959/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9960/// lvalue-to-rvalue cast if it is an lvalue.
9961static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009962 if (E->getType().isNull())
9963 return false;
9964
Nick Lewyckyc190f962017-05-02 01:06:16 +00009965 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +00009966 return false;
9967
Richard Smith2e312c82012-03-03 22:46:17 +00009968 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009969 return false;
9970
9971 if (E->isGLValue()) {
9972 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009973 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009974 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009975 return false;
9976 }
9977
Richard Smith2e312c82012-03-03 22:46:17 +00009978 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009979 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009980}
Richard Smith11562c52011-10-28 17:51:58 +00009981
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009982static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +00009983 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009984 // Fast-path evaluations of integer literals, since we sometimes see files
9985 // containing vast quantities of these.
9986 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9987 Result.Val = APValue(APSInt(L->getValue(),
9988 L->getType()->isUnsignedIntegerType()));
9989 IsConst = true;
9990 return true;
9991 }
James Dennett0492ef02014-03-14 17:44:10 +00009992
9993 // This case should be rare, but we need to check it before we check on
9994 // the type below.
9995 if (Exp->getType().isNull()) {
9996 IsConst = false;
9997 return true;
9998 }
Daniel Jasperffdee092017-05-02 19:21:42 +00009999
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010000 // FIXME: Evaluating values of large array and record types can cause
10001 // performance problems. Only do so in C++11 for now.
10002 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10003 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010004 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010005 IsConst = false;
10006 return true;
10007 }
10008 return false;
10009}
10010
10011
Richard Smith7b553f12011-10-29 00:50:52 +000010012/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010013/// any crazy technique (that has nothing to do with language standards) that
10014/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010015/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10016/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +000010017bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010018 bool IsConst;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010019 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010020 return IsConst;
Daniel Jasperffdee092017-05-02 19:21:42 +000010021
Richard Smith6d4c6582013-11-05 22:18:15 +000010022 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010023 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +000010024}
10025
Jay Foad39c79802011-01-12 09:06:06 +000010026bool Expr::EvaluateAsBooleanCondition(bool &Result,
10027 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010028 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010029 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010030 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010031}
10032
Richard Smithce8eca52015-12-08 03:21:47 +000010033static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10034 Expr::SideEffectsKind SEK) {
10035 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10036 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10037}
10038
Richard Smith5fab0c92011-12-28 19:48:30 +000010039bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10040 SideEffectsKind AllowSideEffects) const {
10041 if (!getType()->isIntegralOrEnumerationType())
10042 return false;
10043
Richard Smith11562c52011-10-28 17:51:58 +000010044 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010045 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +000010046 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010047 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010048
Richard Smith11562c52011-10-28 17:51:58 +000010049 Result = ExprResult.Val.getInt();
10050 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010051}
10052
Richard Trieube234c32016-04-21 21:04:55 +000010053bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10054 SideEffectsKind AllowSideEffects) const {
10055 if (!getType()->isRealFloatingType())
10056 return false;
10057
10058 EvalResult ExprResult;
10059 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10060 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10061 return false;
10062
10063 Result = ExprResult.Val.getFloat();
10064 return true;
10065}
10066
Jay Foad39c79802011-01-12 09:06:06 +000010067bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010068 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010069
John McCall45d55e42010-05-07 21:00:08 +000010070 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010071 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10072 !CheckLValueConstantExpression(Info, getExprLoc(),
10073 Ctx.getLValueReferenceType(getType()), LV))
10074 return false;
10075
Richard Smith2e312c82012-03-03 22:46:17 +000010076 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010077 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010078}
10079
Richard Smithd0b4dd62011-12-19 06:19:21 +000010080bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10081 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010082 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010083 // FIXME: Evaluating initializers for large array and record types can cause
10084 // performance problems. Only do so in C++11 for now.
10085 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010086 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010087 return false;
10088
Richard Smithd0b4dd62011-12-19 06:19:21 +000010089 Expr::EvalStatus EStatus;
10090 EStatus.Diag = &Notes;
10091
Richard Smith0c6124b2015-12-03 01:36:22 +000010092 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10093 ? EvalInfo::EM_ConstantExpression
10094 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010095 InitInfo.setEvaluatingDecl(VD, Value);
10096
10097 LValue LVal;
10098 LVal.set(VD);
10099
Richard Smithfddd3842011-12-30 21:15:51 +000010100 // C++11 [basic.start.init]p2:
10101 // Variables with static storage duration or thread storage duration shall be
10102 // zero-initialized before any other initialization takes place.
10103 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010104 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010105 !VD->getType()->isReferenceType()) {
10106 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010107 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010108 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010109 return false;
10110 }
10111
Richard Smith7525ff62013-05-09 07:14:00 +000010112 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10113 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010114 EStatus.HasSideEffects)
10115 return false;
10116
10117 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10118 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010119}
10120
Richard Smith7b553f12011-10-29 00:50:52 +000010121/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10122/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010123bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010124 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010125 return EvaluateAsRValue(Result, Ctx) &&
10126 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010127}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010128
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010129APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010130 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010131 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010132 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010133 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010134 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010135 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010136 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010137
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010138 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010139}
John McCall864e3962010-05-07 05:32:02 +000010140
Richard Smithe9ff7702013-11-05 22:23:30 +000010141void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010142 bool IsConst;
10143 EvalResult EvalResult;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010144 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010145 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010146 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10147 }
10148}
10149
Richard Smithe6c01442013-06-05 00:46:14 +000010150bool Expr::EvalResult::isGlobalLValue() const {
10151 assert(Val.isLValue());
10152 return IsGlobalLValue(Val.getLValueBase());
10153}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010154
10155
John McCall864e3962010-05-07 05:32:02 +000010156/// isIntegerConstantExpr - this recursive routine will test if an expression is
10157/// an integer constant expression.
10158
10159/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10160/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010161
10162// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010163// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10164// and a (possibly null) SourceLocation indicating the location of the problem.
10165//
John McCall864e3962010-05-07 05:32:02 +000010166// Note that to reduce code duplication, this helper does no evaluation
10167// itself; the caller checks whether the expression is evaluatable, and
10168// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010169// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010170
Dan Gohman28ade552010-07-26 21:25:24 +000010171namespace {
10172
Richard Smith9e575da2012-12-28 13:25:52 +000010173enum ICEKind {
10174 /// This expression is an ICE.
10175 IK_ICE,
10176 /// This expression is not an ICE, but if it isn't evaluated, it's
10177 /// a legal subexpression for an ICE. This return value is used to handle
10178 /// the comma operator in C99 mode, and non-constant subexpressions.
10179 IK_ICEIfUnevaluated,
10180 /// This expression is not an ICE, and is not a legal subexpression for one.
10181 IK_NotICE
10182};
10183
John McCall864e3962010-05-07 05:32:02 +000010184struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010185 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010186 SourceLocation Loc;
10187
Richard Smith9e575da2012-12-28 13:25:52 +000010188 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010189};
10190
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010191}
Dan Gohman28ade552010-07-26 21:25:24 +000010192
Richard Smith9e575da2012-12-28 13:25:52 +000010193static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10194
10195static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010196
Craig Toppera31a8822013-08-22 07:09:37 +000010197static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010198 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010199 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010200 !EVResult.Val.isInt())
10201 return ICEDiag(IK_NotICE, E->getLocStart());
10202
John McCall864e3962010-05-07 05:32:02 +000010203 return NoDiag();
10204}
10205
Craig Toppera31a8822013-08-22 07:09:37 +000010206static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010207 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010208 if (!E->getType()->isIntegralOrEnumerationType())
10209 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010210
10211 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010212#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010213#define STMT(Node, Base) case Expr::Node##Class:
10214#define EXPR(Node, Base)
10215#include "clang/AST/StmtNodes.inc"
10216 case Expr::PredefinedExprClass:
10217 case Expr::FloatingLiteralClass:
10218 case Expr::ImaginaryLiteralClass:
10219 case Expr::StringLiteralClass:
10220 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010221 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010222 case Expr::MemberExprClass:
10223 case Expr::CompoundAssignOperatorClass:
10224 case Expr::CompoundLiteralExprClass:
10225 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010226 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010227 case Expr::ArrayInitLoopExprClass:
10228 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010229 case Expr::NoInitExprClass:
10230 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010231 case Expr::ImplicitValueInitExprClass:
10232 case Expr::ParenListExprClass:
10233 case Expr::VAArgExprClass:
10234 case Expr::AddrLabelExprClass:
10235 case Expr::StmtExprClass:
10236 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010237 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010238 case Expr::CXXDynamicCastExprClass:
10239 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010240 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010241 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010242 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010243 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010244 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010245 case Expr::CXXThisExprClass:
10246 case Expr::CXXThrowExprClass:
10247 case Expr::CXXNewExprClass:
10248 case Expr::CXXDeleteExprClass:
10249 case Expr::CXXPseudoDestructorExprClass:
10250 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010251 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010252 case Expr::DependentScopeDeclRefExprClass:
10253 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010254 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010255 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010256 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010257 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010258 case Expr::CXXTemporaryObjectExprClass:
10259 case Expr::CXXUnresolvedConstructExprClass:
10260 case Expr::CXXDependentScopeMemberExprClass:
10261 case Expr::UnresolvedMemberExprClass:
10262 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010263 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010264 case Expr::ObjCArrayLiteralClass:
10265 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010266 case Expr::ObjCEncodeExprClass:
10267 case Expr::ObjCMessageExprClass:
10268 case Expr::ObjCSelectorExprClass:
10269 case Expr::ObjCProtocolExprClass:
10270 case Expr::ObjCIvarRefExprClass:
10271 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010272 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010273 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010274 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010275 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010276 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010277 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010278 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010279 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010280 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010281 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010282 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010283 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010284 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010285 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010286 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010287 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010288 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010289 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010290 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000010291 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010292 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010293 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010294
Richard Smithf137f932014-01-25 20:50:08 +000010295 case Expr::InitListExprClass: {
10296 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10297 // form "T x = { a };" is equivalent to "T x = a;".
10298 // Unless we're initializing a reference, T is a scalar as it is known to be
10299 // of integral or enumeration type.
10300 if (E->isRValue())
10301 if (cast<InitListExpr>(E)->getNumInits() == 1)
10302 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10303 return ICEDiag(IK_NotICE, E->getLocStart());
10304 }
10305
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010306 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010307 case Expr::GNUNullExprClass:
10308 // GCC considers the GNU __null value to be an integral constant expression.
10309 return NoDiag();
10310
John McCall7c454bb2011-07-15 05:09:51 +000010311 case Expr::SubstNonTypeTemplateParmExprClass:
10312 return
10313 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10314
John McCall864e3962010-05-07 05:32:02 +000010315 case Expr::ParenExprClass:
10316 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010317 case Expr::GenericSelectionExprClass:
10318 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010319 case Expr::IntegerLiteralClass:
10320 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010321 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010322 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010323 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010324 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010325 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010326 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010327 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010328 return NoDiag();
10329 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010330 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010331 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10332 // constant expressions, but they can never be ICEs because an ICE cannot
10333 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010334 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010335 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010336 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010337 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010338 }
Richard Smith6365c912012-02-24 22:12:32 +000010339 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010340 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10341 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010342 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010343 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010344 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010345 // Parameter variables are never constants. Without this check,
10346 // getAnyInitializer() can find a default argument, which leads
10347 // to chaos.
10348 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010349 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010350
10351 // C++ 7.1.5.1p2
10352 // A variable of non-volatile const-qualified integral or enumeration
10353 // type initialized by an ICE can be used in ICEs.
10354 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010355 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010356 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010357
Richard Smithd0b4dd62011-12-19 06:19:21 +000010358 const VarDecl *VD;
10359 // Look for a declaration of this variable that has an initializer, and
10360 // check whether it is an ICE.
10361 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10362 return NoDiag();
10363 else
Richard Smith9e575da2012-12-28 13:25:52 +000010364 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010365 }
10366 }
Richard Smith9e575da2012-12-28 13:25:52 +000010367 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010368 }
John McCall864e3962010-05-07 05:32:02 +000010369 case Expr::UnaryOperatorClass: {
10370 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10371 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010372 case UO_PostInc:
10373 case UO_PostDec:
10374 case UO_PreInc:
10375 case UO_PreDec:
10376 case UO_AddrOf:
10377 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010378 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010379 // C99 6.6/3 allows increment and decrement within unevaluated
10380 // subexpressions of constant expressions, but they can never be ICEs
10381 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010382 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010383 case UO_Extension:
10384 case UO_LNot:
10385 case UO_Plus:
10386 case UO_Minus:
10387 case UO_Not:
10388 case UO_Real:
10389 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010390 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010391 }
Richard Smith9e575da2012-12-28 13:25:52 +000010392
John McCall864e3962010-05-07 05:32:02 +000010393 // OffsetOf falls through here.
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010394 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010395 }
10396 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010397 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10398 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10399 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10400 // compliance: we should warn earlier for offsetof expressions with
10401 // array subscripts that aren't ICEs, and if the array subscripts
10402 // are ICEs, the value of the offsetof must be an integer constant.
10403 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010404 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010405 case Expr::UnaryExprOrTypeTraitExprClass: {
10406 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10407 if ((Exp->getKind() == UETT_SizeOf) &&
10408 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010409 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010410 return NoDiag();
10411 }
10412 case Expr::BinaryOperatorClass: {
10413 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10414 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010415 case BO_PtrMemD:
10416 case BO_PtrMemI:
10417 case BO_Assign:
10418 case BO_MulAssign:
10419 case BO_DivAssign:
10420 case BO_RemAssign:
10421 case BO_AddAssign:
10422 case BO_SubAssign:
10423 case BO_ShlAssign:
10424 case BO_ShrAssign:
10425 case BO_AndAssign:
10426 case BO_XorAssign:
10427 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000010428 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10429 // constant expressions, but they can never be ICEs because an ICE cannot
10430 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010431 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010432
John McCalle3027922010-08-25 11:45:40 +000010433 case BO_Mul:
10434 case BO_Div:
10435 case BO_Rem:
10436 case BO_Add:
10437 case BO_Sub:
10438 case BO_Shl:
10439 case BO_Shr:
10440 case BO_LT:
10441 case BO_GT:
10442 case BO_LE:
10443 case BO_GE:
10444 case BO_EQ:
10445 case BO_NE:
10446 case BO_And:
10447 case BO_Xor:
10448 case BO_Or:
10449 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010450 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10451 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010452 if (Exp->getOpcode() == BO_Div ||
10453 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010454 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010455 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010456 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010457 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010458 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010459 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010460 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010461 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010462 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010463 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010464 }
10465 }
10466 }
John McCalle3027922010-08-25 11:45:40 +000010467 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010468 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010469 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10470 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010471 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10472 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010473 } else {
10474 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010475 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010476 }
10477 }
Richard Smith9e575da2012-12-28 13:25:52 +000010478 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010479 }
John McCalle3027922010-08-25 11:45:40 +000010480 case BO_LAnd:
10481 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010482 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10483 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010484 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010485 // Rare case where the RHS has a comma "side-effect"; we need
10486 // to actually check the condition to see whether the side
10487 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010488 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010489 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010490 return RHSResult;
10491 return NoDiag();
10492 }
10493
Richard Smith9e575da2012-12-28 13:25:52 +000010494 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010495 }
10496 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010497 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010498 }
10499 case Expr::ImplicitCastExprClass:
10500 case Expr::CStyleCastExprClass:
10501 case Expr::CXXFunctionalCastExprClass:
10502 case Expr::CXXStaticCastExprClass:
10503 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010504 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010505 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010506 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010507 if (isa<ExplicitCastExpr>(E)) {
10508 if (const FloatingLiteral *FL
10509 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10510 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10511 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10512 APSInt IgnoredVal(DestWidth, !DestSigned);
10513 bool Ignored;
10514 // If the value does not fit in the destination type, the behavior is
10515 // undefined, so we are not required to treat it as a constant
10516 // expression.
10517 if (FL->getValue().convertToInteger(IgnoredVal,
10518 llvm::APFloat::rmTowardZero,
10519 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010520 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010521 return NoDiag();
10522 }
10523 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010524 switch (cast<CastExpr>(E)->getCastKind()) {
10525 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010526 case CK_AtomicToNonAtomic:
10527 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010528 case CK_NoOp:
10529 case CK_IntegralToBoolean:
10530 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010531 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010532 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010533 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010534 }
John McCall864e3962010-05-07 05:32:02 +000010535 }
John McCallc07a0c72011-02-17 10:25:35 +000010536 case Expr::BinaryConditionalOperatorClass: {
10537 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10538 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010539 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010540 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010541 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10542 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10543 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010544 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010545 return FalseResult;
10546 }
John McCall864e3962010-05-07 05:32:02 +000010547 case Expr::ConditionalOperatorClass: {
10548 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10549 // If the condition (ignoring parens) is a __builtin_constant_p call,
10550 // then only the true side is actually considered in an integer constant
10551 // expression, and it is fully evaluated. This is an important GNU
10552 // extension. See GCC PR38377 for discussion.
10553 if (const CallExpr *CallCE
10554 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010555 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010556 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010557 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010558 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010559 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010560
Richard Smithf57d8cb2011-12-09 22:58:01 +000010561 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10562 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010563
Richard Smith9e575da2012-12-28 13:25:52 +000010564 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010565 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010566 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010567 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010568 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010569 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010570 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010571 return NoDiag();
10572 // Rare case where the diagnostics depend on which side is evaluated
10573 // Note that if we get here, CondResult is 0, and at least one of
10574 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010575 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010576 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010577 return TrueResult;
10578 }
10579 case Expr::CXXDefaultArgExprClass:
10580 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010581 case Expr::CXXDefaultInitExprClass:
10582 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010583 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010584 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010585 }
10586 }
10587
David Blaikiee4d798f2012-01-20 21:50:17 +000010588 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010589}
10590
Richard Smithf57d8cb2011-12-09 22:58:01 +000010591/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010592static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010593 const Expr *E,
10594 llvm::APSInt *Value,
10595 SourceLocation *Loc) {
10596 if (!E->getType()->isIntegralOrEnumerationType()) {
10597 if (Loc) *Loc = E->getExprLoc();
10598 return false;
10599 }
10600
Richard Smith66e05fe2012-01-18 05:21:49 +000010601 APValue Result;
10602 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010603 return false;
10604
Richard Smith98710fc2014-11-13 23:03:19 +000010605 if (!Result.isInt()) {
10606 if (Loc) *Loc = E->getExprLoc();
10607 return false;
10608 }
10609
Richard Smith66e05fe2012-01-18 05:21:49 +000010610 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010611 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010612}
10613
Craig Toppera31a8822013-08-22 07:09:37 +000010614bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10615 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010616 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010617 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010618
Richard Smith9e575da2012-12-28 13:25:52 +000010619 ICEDiag D = CheckICE(this, Ctx);
10620 if (D.Kind != IK_ICE) {
10621 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010622 return false;
10623 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010624 return true;
10625}
10626
Craig Toppera31a8822013-08-22 07:09:37 +000010627bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010628 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010629 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010630 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10631
10632 if (!isIntegerConstantExpr(Ctx, Loc))
10633 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010634 // The only possible side-effects here are due to UB discovered in the
10635 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10636 // required to treat the expression as an ICE, so we produce the folded
10637 // value.
10638 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010639 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010640 return true;
10641}
Richard Smith66e05fe2012-01-18 05:21:49 +000010642
Craig Toppera31a8822013-08-22 07:09:37 +000010643bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010644 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010645}
10646
Craig Toppera31a8822013-08-22 07:09:37 +000010647bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010648 SourceLocation *Loc) const {
10649 // We support this checking in C++98 mode in order to diagnose compatibility
10650 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010651 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010652
Richard Smith98a0a492012-02-14 21:38:30 +000010653 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010654 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010655 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010656 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010657 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010658
10659 APValue Scratch;
10660 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10661
10662 if (!Diags.empty()) {
10663 IsConstExpr = false;
10664 if (Loc) *Loc = Diags[0].first;
10665 } else if (!IsConstExpr) {
10666 // FIXME: This shouldn't happen.
10667 if (Loc) *Loc = getExprLoc();
10668 }
10669
10670 return IsConstExpr;
10671}
Richard Smith253c2a32012-01-27 01:14:48 +000010672
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010673bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10674 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010675 ArrayRef<const Expr*> Args,
10676 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010677 Expr::EvalStatus Status;
10678 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10679
George Burgess IV177399e2017-01-09 04:12:14 +000010680 LValue ThisVal;
10681 const LValue *ThisPtr = nullptr;
10682 if (This) {
10683#ifndef NDEBUG
10684 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10685 assert(MD && "Don't provide `this` for non-methods.");
10686 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10687#endif
10688 if (EvaluateObjectArgument(Info, This, ThisVal))
10689 ThisPtr = &ThisVal;
10690 if (Info.EvalStatus.HasSideEffects)
10691 return false;
10692 }
10693
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010694 ArgVector ArgValues(Args.size());
10695 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10696 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010697 if ((*I)->isValueDependent() ||
10698 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010699 // If evaluation fails, throw away the argument entirely.
10700 ArgValues[I - Args.begin()] = APValue();
10701 if (Info.EvalStatus.HasSideEffects)
10702 return false;
10703 }
10704
10705 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010706 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010707 ArgValues.data());
10708 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10709}
10710
Richard Smith253c2a32012-01-27 01:14:48 +000010711bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010712 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010713 PartialDiagnosticAt> &Diags) {
10714 // FIXME: It would be useful to check constexpr function templates, but at the
10715 // moment the constant expression evaluator cannot cope with the non-rigorous
10716 // ASTs which we build for dependent expressions.
10717 if (FD->isDependentContext())
10718 return true;
10719
10720 Expr::EvalStatus Status;
10721 Status.Diag = &Diags;
10722
Richard Smith6d4c6582013-11-05 22:18:15 +000010723 EvalInfo Info(FD->getASTContext(), Status,
10724 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010725
10726 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010727 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010728
Richard Smith7525ff62013-05-09 07:14:00 +000010729 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010730 // is a temporary being used as the 'this' pointer.
10731 LValue This;
10732 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010733 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010734
Richard Smith253c2a32012-01-27 01:14:48 +000010735 ArrayRef<const Expr*> Args;
10736
Richard Smith2e312c82012-03-03 22:46:17 +000010737 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010738 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10739 // Evaluate the call as a constant initializer, to allow the construction
10740 // of objects of non-literal types.
10741 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010742 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10743 } else {
10744 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010745 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010746 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010747 }
Richard Smith253c2a32012-01-27 01:14:48 +000010748
10749 return Diags.empty();
10750}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010751
10752bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10753 const FunctionDecl *FD,
10754 SmallVectorImpl<
10755 PartialDiagnosticAt> &Diags) {
10756 Expr::EvalStatus Status;
10757 Status.Diag = &Diags;
10758
10759 EvalInfo Info(FD->getASTContext(), Status,
10760 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10761
10762 // Fabricate a call stack frame to give the arguments a plausible cover story.
10763 ArrayRef<const Expr*> Args;
10764 ArgVector ArgValues(0);
10765 bool Success = EvaluateArgs(Args, ArgValues, Info);
10766 (void)Success;
10767 assert(Success &&
10768 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010769 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010770
10771 APValue ResultScratch;
10772 Evaluate(ResultScratch, Info, E);
10773 return Diags.empty();
10774}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010775
10776bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10777 unsigned Type) const {
10778 if (!getType()->isPointerType())
10779 return false;
10780
10781 Expr::EvalStatus Status;
10782 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010783 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010784}