blob: c19812e341c03209eda05090661cc3f7d44c8fe4 [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,
Daniel Jasperffdee092017-05-02 19:21:42 +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()) {
161 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,
251 MostDerivedType, IsArray);
252 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.
321 MostDerivedArraySize = std::numeric_limits<uint64_t>::max() / 2;
322 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 Kleckner06df4022016-12-13 19:48:32 +0000540 struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) 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
Richard Smith410306b2016-12-12 02:53:20 +0000576 /// The current array initialization index, if we're performing array
577 /// initialization.
578 uint64_t ArrayInitIndex = -1;
579
Richard Smith357362d2011-12-13 06:39:58 +0000580 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
581 /// notes attached to it will also be stored, otherwise they will not be.
582 bool HasActiveDiagnostic;
583
Richard Smith0c6124b2015-12-03 01:36:22 +0000584 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
585 /// fold (not just why it's not strictly a constant expression)?
586 bool HasFoldFailureDiagnostic;
587
George Burgess IV8c892b52016-05-25 22:31:54 +0000588 /// \brief Whether or not we're currently speculatively evaluating.
589 bool IsSpeculativelyEvaluating;
590
Richard Smith6d4c6582013-11-05 22:18:15 +0000591 enum EvaluationMode {
592 /// Evaluate as a constant expression. Stop if we find that the expression
593 /// is not a constant expression.
594 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000595
Richard Smith6d4c6582013-11-05 22:18:15 +0000596 /// Evaluate as a potential constant expression. Keep going if we hit a
597 /// construct that we can't evaluate yet (because we don't yet know the
598 /// value of something) but stop if we hit something that could never be
599 /// a constant expression.
600 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000601
Richard Smith6d4c6582013-11-05 22:18:15 +0000602 /// Fold the expression to a constant. Stop if we hit a side-effect that
603 /// we can't model.
604 EM_ConstantFold,
605
606 /// Evaluate the expression looking for integer overflow and similar
607 /// issues. Don't worry about side-effects, and try to visit all
608 /// subexpressions.
609 EM_EvaluateForOverflow,
610
611 /// Evaluate in any way we know how. Don't worry about side-effects that
612 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000613 EM_IgnoreSideEffects,
614
615 /// Evaluate as a constant expression. Stop if we find that the expression
616 /// is not a constant expression. Some expressions can be retried in the
617 /// optimizer if we don't constant fold them here, but in an unevaluated
618 /// context we try to fold them immediately since the optimizer never
619 /// gets a chance to look at it.
620 EM_ConstantExpressionUnevaluated,
621
622 /// Evaluate as a potential constant expression. Keep going if we hit a
623 /// construct that we can't evaluate yet (because we don't yet know the
624 /// value of something) but stop if we hit something that could never be
625 /// a constant expression. Some expressions can be retried in the
626 /// optimizer if we don't constant fold them here, but in an unevaluated
627 /// context we try to fold them immediately since the optimizer never
628 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000629 EM_PotentialConstantExpressionUnevaluated,
630
George Burgess IVf9013bf2017-02-10 22:52:29 +0000631 /// Evaluate as a constant expression. In certain scenarios, if:
632 /// - we find a MemberExpr with a base that can't be evaluated, or
633 /// - we find a variable initialized with a call to a function that has
634 /// the alloc_size attribute on it
635 /// then we may consider evaluation to have succeeded.
636 ///
George Burgess IVe3763372016-12-22 02:50:20 +0000637 /// In either case, the LValue returned shall have an invalid base; in the
638 /// former, the base will be the invalid MemberExpr, in the latter, the
639 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
640 /// said CallExpr.
641 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000642 } EvalMode;
643
644 /// Are we checking whether the expression is a potential constant
645 /// expression?
646 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000647 return EvalMode == EM_PotentialConstantExpression ||
648 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000649 }
650
651 /// Are we checking an expression for overflow?
652 // FIXME: We should check for any kind of undefined or suspicious behavior
653 // in such constructs, not just overflow.
654 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
655
656 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000657 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000658 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000659 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000660 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
661 EvaluatingDecl((const ValueDecl *)nullptr),
662 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000663 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
664 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000665
Richard Smith7525ff62013-05-09 07:14:00 +0000666 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
667 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000668 EvaluatingDeclValue = &Value;
669 }
670
David Blaikiebbafb8a2012-03-11 07:00:24 +0000671 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000672
Richard Smith357362d2011-12-13 06:39:58 +0000673 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000674 // Don't perform any constexpr calls (other than the call we're checking)
675 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000676 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000677 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000678 if (NextCallIndex == 0) {
679 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000680 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000681 return false;
682 }
Richard Smith357362d2011-12-13 06:39:58 +0000683 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
684 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000685 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000686 << getLangOpts().ConstexprCallDepth;
687 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000688 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000689
Richard Smithb228a862012-02-15 02:18:13 +0000690 CallStackFrame *getCallFrame(unsigned CallIndex) {
691 assert(CallIndex && "no call index in getCallFrame");
692 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
693 // be null in this loop.
694 CallStackFrame *Frame = CurrentCall;
695 while (Frame->Index > CallIndex)
696 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000697 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000698 }
699
Richard Smitha3d3bd22013-05-08 02:12:03 +0000700 bool nextStep(const Stmt *S) {
701 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000702 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000703 return false;
704 }
705 --StepsLeft;
706 return true;
707 }
708
Richard Smith357362d2011-12-13 06:39:58 +0000709 private:
710 /// Add a diagnostic to the diagnostics list.
711 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
712 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
713 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
714 return EvalStatus.Diag->back().second;
715 }
716
Richard Smithf6f003a2011-12-16 19:06:07 +0000717 /// Add notes containing a call stack to the current point of evaluation.
718 void addCallStack(unsigned Limit);
719
Faisal Valie690b7a2016-07-02 22:34:24 +0000720 private:
721 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
722 unsigned ExtraNotes, bool IsCCEDiag) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000723
Richard Smith92b1ce02011-12-12 09:28:41 +0000724 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000725 // If we have a prior diagnostic, it will be noting that the expression
726 // isn't a constant expression. This diagnostic is more important,
727 // unless we require this evaluation to produce a constant expression.
728 //
729 // FIXME: We might want to show both diagnostics to the user in
730 // EM_ConstantFold mode.
731 if (!EvalStatus.Diag->empty()) {
732 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000733 case EM_ConstantFold:
734 case EM_IgnoreSideEffects:
735 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000736 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000737 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000738 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000739 case EM_ConstantExpression:
740 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000741 case EM_ConstantExpressionUnevaluated:
742 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000743 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000744 HasActiveDiagnostic = false;
745 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000746 }
747 }
748
Richard Smithf6f003a2011-12-16 19:06:07 +0000749 unsigned CallStackNotes = CallStackDepth - 1;
750 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
751 if (Limit)
752 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000753 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000754 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000755
Richard Smith357362d2011-12-13 06:39:58 +0000756 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000757 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000758 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000759 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
760 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000761 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000762 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000763 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000764 }
Richard Smith357362d2011-12-13 06:39:58 +0000765 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000766 return OptionalDiagnostic();
767 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000768 public:
769 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
770 OptionalDiagnostic
771 FFDiag(SourceLocation Loc,
772 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
773 unsigned ExtraNotes = 0) {
774 return Diag(Loc, DiagId, ExtraNotes, false);
775 }
Daniel Jasperffdee092017-05-02 19:21:42 +0000776
Faisal Valie690b7a2016-07-02 22:34:24 +0000777 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000778 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000779 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000780 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000781 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000782 HasActiveDiagnostic = false;
783 return OptionalDiagnostic();
784 }
785
Richard Smith92b1ce02011-12-12 09:28:41 +0000786 /// Diagnose that the evaluation does not produce a C++11 core constant
787 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000788 ///
789 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
790 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000791 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000792 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000793 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000794 // Don't override a previous diagnostic. Don't bother collecting
795 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000796 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000797 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000798 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000799 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000800 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000801 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000802 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
803 = diag::note_invalid_subexpr_in_const_expr,
804 unsigned ExtraNotes = 0) {
805 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
806 }
Richard Smith357362d2011-12-13 06:39:58 +0000807 /// Add a note to a prior diagnostic.
808 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
809 if (!HasActiveDiagnostic)
810 return OptionalDiagnostic();
811 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000812 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000813
814 /// Add a stack of notes to a prior diagnostic.
815 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
816 if (HasActiveDiagnostic) {
817 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
818 Diags.begin(), Diags.end());
819 }
820 }
Richard Smith253c2a32012-01-27 01:14:48 +0000821
Richard Smith6d4c6582013-11-05 22:18:15 +0000822 /// Should we continue evaluation after encountering a side-effect that we
823 /// couldn't model?
824 bool keepEvaluatingAfterSideEffect() {
825 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000826 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000827 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000828 case EM_EvaluateForOverflow:
829 case EM_IgnoreSideEffects:
830 return true;
831
Richard Smith6d4c6582013-11-05 22:18:15 +0000832 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000833 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000834 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000835 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000836 return false;
837 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000838 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000839 }
840
841 /// Note that we have had a side-effect, and determine whether we should
842 /// keep evaluating.
843 bool noteSideEffect() {
844 EvalStatus.HasSideEffects = true;
845 return keepEvaluatingAfterSideEffect();
846 }
847
Richard Smithce8eca52015-12-08 03:21:47 +0000848 /// Should we continue evaluation after encountering undefined behavior?
849 bool keepEvaluatingAfterUndefinedBehavior() {
850 switch (EvalMode) {
851 case EM_EvaluateForOverflow:
852 case EM_IgnoreSideEffects:
853 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000854 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000855 return true;
856
857 case EM_PotentialConstantExpression:
858 case EM_PotentialConstantExpressionUnevaluated:
859 case EM_ConstantExpression:
860 case EM_ConstantExpressionUnevaluated:
861 return false;
862 }
863 llvm_unreachable("Missed EvalMode case");
864 }
865
866 /// Note that we hit something that was technically undefined behavior, but
867 /// that we can evaluate past it (such as signed overflow or floating-point
868 /// division by zero.)
869 bool noteUndefinedBehavior() {
870 EvalStatus.HasUndefinedBehavior = true;
871 return keepEvaluatingAfterUndefinedBehavior();
872 }
873
Richard Smith253c2a32012-01-27 01:14:48 +0000874 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000875 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000876 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000877 if (!StepsLeft)
878 return false;
879
880 switch (EvalMode) {
881 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000882 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000883 case EM_EvaluateForOverflow:
884 return true;
885
886 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000887 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000888 case EM_ConstantFold:
889 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000890 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000891 return false;
892 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000893 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000894 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000895
George Burgess IV8c892b52016-05-25 22:31:54 +0000896 /// Notes that we failed to evaluate an expression that other expressions
897 /// directly depend on, and determine if we should keep evaluating. This
898 /// should only be called if we actually intend to keep evaluating.
899 ///
900 /// Call noteSideEffect() instead if we may be able to ignore the value that
901 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
902 ///
903 /// (Foo(), 1) // use noteSideEffect
904 /// (Foo() || true) // use noteSideEffect
905 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000906 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000907 // Failure when evaluating some expression often means there is some
908 // subexpression whose evaluation was skipped. Therefore, (because we
909 // don't track whether we skipped an expression when unwinding after an
910 // evaluation failure) every evaluation failure that bubbles up from a
911 // subexpression implies that a side-effect has potentially happened. We
912 // skip setting the HasSideEffects flag to true until we decide to
913 // continue evaluating after that point, which happens here.
914 bool KeepGoing = keepEvaluatingAfterFailure();
915 EvalStatus.HasSideEffects |= KeepGoing;
916 return KeepGoing;
917 }
918
Richard Smith410306b2016-12-12 02:53:20 +0000919 class ArrayInitLoopIndex {
920 EvalInfo &Info;
921 uint64_t OuterIndex;
922
923 public:
924 ArrayInitLoopIndex(EvalInfo &Info)
925 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
926 Info.ArrayInitIndex = 0;
927 }
928 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
929
930 operator uint64_t&() { return Info.ArrayInitIndex; }
931 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000932 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000933
934 /// Object used to treat all foldable expressions as constant expressions.
935 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000936 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000937 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000938 bool HadNoPriorDiags;
939 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000940
Richard Smith6d4c6582013-11-05 22:18:15 +0000941 explicit FoldConstant(EvalInfo &Info, bool Enabled)
942 : Info(Info),
943 Enabled(Enabled),
944 HadNoPriorDiags(Info.EvalStatus.Diag &&
945 Info.EvalStatus.Diag->empty() &&
946 !Info.EvalStatus.HasSideEffects),
947 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000948 if (Enabled &&
949 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
950 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000951 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000952 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000953 void keepDiagnostics() { Enabled = false; }
954 ~FoldConstant() {
955 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000956 !Info.EvalStatus.HasSideEffects)
957 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000958 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000959 }
960 };
Richard Smith17100ba2012-02-16 02:46:34 +0000961
George Burgess IV3a03fab2015-09-04 21:28:13 +0000962 /// RAII object used to treat the current evaluation as the correct pointer
963 /// offset fold for the current EvalMode
964 struct FoldOffsetRAII {
965 EvalInfo &Info;
966 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +0000967 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +0000968 : Info(Info), OldMode(Info.EvalMode) {
969 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +0000970 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000971 }
972
973 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
974 };
975
George Burgess IV8c892b52016-05-25 22:31:54 +0000976 /// RAII object used to optionally suppress diagnostics and side-effects from
977 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000978 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000979 /// Pair of EvalInfo, and a bit that stores whether or not we were
980 /// speculatively evaluating when we created this RAII.
981 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000982 Expr::EvalStatus Old;
983
George Burgess IV8c892b52016-05-25 22:31:54 +0000984 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
985 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
986 Old = Other.Old;
987 Other.InfoAndOldSpecEval.setPointer(nullptr);
988 }
989
990 void maybeRestoreState() {
991 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
992 if (!Info)
993 return;
994
995 Info->EvalStatus = Old;
996 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
997 }
998
Richard Smith17100ba2012-02-16 02:46:34 +0000999 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001000 SpeculativeEvaluationRAII() = default;
1001
1002 SpeculativeEvaluationRAII(
1003 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1004 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
1005 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +00001006 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001007 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001008 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001009
1010 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1011 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1012 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001013 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001014
1015 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1016 maybeRestoreState();
1017 moveFromAndCancel(std::move(Other));
1018 return *this;
1019 }
1020
1021 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001022 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001023
1024 /// RAII object wrapping a full-expression or block scope, and handling
1025 /// the ending of the lifetime of temporaries created within it.
1026 template<bool IsFullExpression>
1027 class ScopeRAII {
1028 EvalInfo &Info;
1029 unsigned OldStackSize;
1030 public:
1031 ScopeRAII(EvalInfo &Info)
1032 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1033 ~ScopeRAII() {
1034 // Body moved to a static method to encourage the compiler to inline away
1035 // instances of this class.
1036 cleanup(Info, OldStackSize);
1037 }
1038 private:
1039 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1040 unsigned NewEnd = OldStackSize;
1041 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1042 I != N; ++I) {
1043 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1044 // Full-expression cleanup of a lifetime-extended temporary: nothing
1045 // to do, just move this cleanup to the right place in the stack.
1046 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1047 ++NewEnd;
1048 } else {
1049 // End the lifetime of the object.
1050 Info.CleanupStack[I].endLifetime();
1051 }
1052 }
1053 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1054 Info.CleanupStack.end());
1055 }
1056 };
1057 typedef ScopeRAII<false> BlockScopeRAII;
1058 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001059}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001060
Richard Smitha8105bc2012-01-06 16:39:00 +00001061bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1062 CheckSubobjectKind CSK) {
1063 if (Invalid)
1064 return false;
1065 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001066 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001067 << CSK;
1068 setInvalid();
1069 return false;
1070 }
1071 return true;
1072}
1073
1074void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001075 const Expr *E,
1076 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001077 // If we're complaining, we must be able to statically determine the size of
1078 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001079 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001080 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001081 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001082 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001083 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001084 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001085 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001086 setInvalid();
1087}
1088
Richard Smithf6f003a2011-12-16 19:06:07 +00001089CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1090 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001091 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001092 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1093 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001094 Info.CurrentCall = this;
1095 ++Info.CallStackDepth;
1096}
1097
1098CallStackFrame::~CallStackFrame() {
1099 assert(Info.CurrentCall == this && "calls retired out of order");
1100 --Info.CallStackDepth;
1101 Info.CurrentCall = Caller;
1102}
1103
Richard Smith08d6a2c2013-07-24 07:11:57 +00001104APValue &CallStackFrame::createTemporary(const void *Key,
1105 bool IsLifetimeExtended) {
1106 APValue &Result = Temporaries[Key];
1107 assert(Result.isUninit() && "temporary created multiple times");
1108 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1109 return Result;
1110}
1111
Richard Smith84401042013-06-03 05:03:02 +00001112static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001113
1114void EvalInfo::addCallStack(unsigned Limit) {
1115 // Determine which calls to skip, if any.
1116 unsigned ActiveCalls = CallStackDepth - 1;
1117 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1118 if (Limit && Limit < ActiveCalls) {
1119 SkipStart = Limit / 2 + Limit % 2;
1120 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001121 }
1122
Richard Smithf6f003a2011-12-16 19:06:07 +00001123 // Walk the call stack and add the diagnostics.
1124 unsigned CallIdx = 0;
1125 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1126 Frame = Frame->Caller, ++CallIdx) {
1127 // Skip this call?
1128 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1129 if (CallIdx == SkipStart) {
1130 // Note that we're skipping calls.
1131 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1132 << unsigned(ActiveCalls - Limit);
1133 }
1134 continue;
1135 }
1136
Richard Smith5179eb72016-06-28 19:03:57 +00001137 // Use a different note for an inheriting constructor, because from the
1138 // user's perspective it's not really a function at all.
1139 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1140 if (CD->isInheritingConstructor()) {
1141 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1142 << CD->getParent();
1143 continue;
1144 }
1145 }
1146
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001147 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001148 llvm::raw_svector_ostream Out(Buffer);
1149 describeCall(Frame, Out);
1150 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1151 }
1152}
1153
1154namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001155 struct ComplexValue {
1156 private:
1157 bool IsInt;
1158
1159 public:
1160 APSInt IntReal, IntImag;
1161 APFloat FloatReal, FloatImag;
1162
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001163 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001164
1165 void makeComplexFloat() { IsInt = false; }
1166 bool isComplexFloat() const { return !IsInt; }
1167 APFloat &getComplexFloatReal() { return FloatReal; }
1168 APFloat &getComplexFloatImag() { return FloatImag; }
1169
1170 void makeComplexInt() { IsInt = true; }
1171 bool isComplexInt() const { return IsInt; }
1172 APSInt &getComplexIntReal() { return IntReal; }
1173 APSInt &getComplexIntImag() { return IntImag; }
1174
Richard Smith2e312c82012-03-03 22:46:17 +00001175 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001176 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001177 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001178 else
Richard Smith2e312c82012-03-03 22:46:17 +00001179 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001180 }
Richard Smith2e312c82012-03-03 22:46:17 +00001181 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001182 assert(v.isComplexFloat() || v.isComplexInt());
1183 if (v.isComplexFloat()) {
1184 makeComplexFloat();
1185 FloatReal = v.getComplexFloatReal();
1186 FloatImag = v.getComplexFloatImag();
1187 } else {
1188 makeComplexInt();
1189 IntReal = v.getComplexIntReal();
1190 IntImag = v.getComplexIntImag();
1191 }
1192 }
John McCall93d91dc2010-05-07 17:22:02 +00001193 };
John McCall45d55e42010-05-07 21:00:08 +00001194
1195 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001196 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001197 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001198 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001199 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001200 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001201 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001202
Richard Smithce40ad62011-11-12 22:28:03 +00001203 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001204 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001205 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001206 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001207 SubobjectDesignator &getLValueDesignator() { return Designator; }
1208 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001209 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001210
Richard Smith2e312c82012-03-03 22:46:17 +00001211 void moveInto(APValue &V) const {
1212 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001213 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1214 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001215 else {
1216 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Daniel Jasperffdee092017-05-02 19:21:42 +00001217 assert(!Designator.FirstEntryIsAnUnsizedArray &&
1218 "Unsized array with a valid base?");
Richard Smith2e312c82012-03-03 22:46:17 +00001219 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001220 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001221 }
John McCall45d55e42010-05-07 21:00:08 +00001222 }
Richard Smith2e312c82012-03-03 22:46:17 +00001223 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001224 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001225 Base = V.getLValueBase();
1226 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001227 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001228 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001229 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001230 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001231 }
1232
Tim Northover01503332017-05-26 02:16:00 +00001233 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001234#ifndef NDEBUG
1235 // We only allow a few types of invalid bases. Enforce that here.
1236 if (BInvalid) {
1237 const auto *E = B.get<const Expr *>();
1238 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1239 "Unexpected type of invalid base");
1240 }
1241#endif
1242
Richard Smithce40ad62011-11-12 22:28:03 +00001243 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001244 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001245 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001246 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001247 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001248 IsNullPtr = false;
1249 }
1250
1251 void setNull(QualType PointerTy, uint64_t TargetVal) {
1252 Base = (Expr *)nullptr;
1253 Offset = CharUnits::fromQuantity(TargetVal);
1254 InvalidBase = false;
1255 CallIndex = 0;
1256 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1257 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001258 }
1259
George Burgess IV3a03fab2015-09-04 21:28:13 +00001260 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1261 set(B, I, true);
1262 }
1263
Richard Smitha8105bc2012-01-06 16:39:00 +00001264 // Check that this LValue is not based on a null pointer. If it is, produce
1265 // a diagnostic and mark the designator as invalid.
1266 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1267 CheckSubobjectKind CSK) {
1268 if (Designator.Invalid)
1269 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001270 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001271 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001272 << CSK;
1273 Designator.setInvalid();
1274 return false;
1275 }
1276 return true;
1277 }
1278
1279 // Check this LValue refers to an object. If not, set the designator to be
1280 // invalid and emit a diagnostic.
1281 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001282 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001283 Designator.checkSubobject(Info, E, CSK);
1284 }
1285
1286 void addDecl(EvalInfo &Info, const Expr *E,
1287 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001288 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1289 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001290 }
Daniel Jasperffdee092017-05-02 19:21:42 +00001291 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1292 assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1293 assert(isBaseAnAllocSizeCall(Base) &&
1294 "Only alloc_size bases can have unsized arrays");
1295 Designator.FirstEntryIsAnUnsizedArray = true;
1296 Designator.addUnsizedArrayUnchecked(ElemTy);
George Burgess IVe3763372016-12-22 02:50:20 +00001297 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001298 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001299 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1300 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001301 }
Richard Smith66c96992012-02-18 22:04:06 +00001302 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001303 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1304 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001305 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001306 void clearIsNullPointer() {
1307 IsNullPtr = false;
1308 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001309 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1310 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001311 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1312 // but we're not required to diagnose it and it's valid in C++.)
1313 if (!Index)
1314 return;
1315
1316 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1317 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1318 // offsets.
1319 uint64_t Offset64 = Offset.getQuantity();
1320 uint64_t ElemSize64 = ElementSize.getQuantity();
1321 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1322 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1323
1324 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001325 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001326 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001327 }
1328 void adjustOffset(CharUnits N) {
1329 Offset += N;
1330 if (N.getQuantity())
1331 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001332 }
John McCall45d55e42010-05-07 21:00:08 +00001333 };
Richard Smith027bf112011-11-17 22:56:20 +00001334
1335 struct MemberPtr {
1336 MemberPtr() {}
1337 explicit MemberPtr(const ValueDecl *Decl) :
1338 DeclAndIsDerivedMember(Decl, false), Path() {}
1339
1340 /// The member or (direct or indirect) field referred to by this member
1341 /// pointer, or 0 if this is a null member pointer.
1342 const ValueDecl *getDecl() const {
1343 return DeclAndIsDerivedMember.getPointer();
1344 }
1345 /// Is this actually a member of some type derived from the relevant class?
1346 bool isDerivedMember() const {
1347 return DeclAndIsDerivedMember.getInt();
1348 }
1349 /// Get the class which the declaration actually lives in.
1350 const CXXRecordDecl *getContainingRecord() const {
1351 return cast<CXXRecordDecl>(
1352 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1353 }
1354
Richard Smith2e312c82012-03-03 22:46:17 +00001355 void moveInto(APValue &V) const {
1356 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001357 }
Richard Smith2e312c82012-03-03 22:46:17 +00001358 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001359 assert(V.isMemberPointer());
1360 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1361 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1362 Path.clear();
1363 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1364 Path.insert(Path.end(), P.begin(), P.end());
1365 }
1366
1367 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1368 /// whether the member is a member of some class derived from the class type
1369 /// of the member pointer.
1370 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1371 /// Path - The path of base/derived classes from the member declaration's
1372 /// class (exclusive) to the class type of the member pointer (inclusive).
1373 SmallVector<const CXXRecordDecl*, 4> Path;
1374
1375 /// Perform a cast towards the class of the Decl (either up or down the
1376 /// hierarchy).
1377 bool castBack(const CXXRecordDecl *Class) {
1378 assert(!Path.empty());
1379 const CXXRecordDecl *Expected;
1380 if (Path.size() >= 2)
1381 Expected = Path[Path.size() - 2];
1382 else
1383 Expected = getContainingRecord();
1384 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1385 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1386 // if B does not contain the original member and is not a base or
1387 // derived class of the class containing the original member, the result
1388 // of the cast is undefined.
1389 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1390 // (D::*). We consider that to be a language defect.
1391 return false;
1392 }
1393 Path.pop_back();
1394 return true;
1395 }
1396 /// Perform a base-to-derived member pointer cast.
1397 bool castToDerived(const CXXRecordDecl *Derived) {
1398 if (!getDecl())
1399 return true;
1400 if (!isDerivedMember()) {
1401 Path.push_back(Derived);
1402 return true;
1403 }
1404 if (!castBack(Derived))
1405 return false;
1406 if (Path.empty())
1407 DeclAndIsDerivedMember.setInt(false);
1408 return true;
1409 }
1410 /// Perform a derived-to-base member pointer cast.
1411 bool castToBase(const CXXRecordDecl *Base) {
1412 if (!getDecl())
1413 return true;
1414 if (Path.empty())
1415 DeclAndIsDerivedMember.setInt(true);
1416 if (isDerivedMember()) {
1417 Path.push_back(Base);
1418 return true;
1419 }
1420 return castBack(Base);
1421 }
1422 };
Richard Smith357362d2011-12-13 06:39:58 +00001423
Richard Smith7bb00672012-02-01 01:42:44 +00001424 /// Compare two member pointers, which are assumed to be of the same type.
1425 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1426 if (!LHS.getDecl() || !RHS.getDecl())
1427 return !LHS.getDecl() && !RHS.getDecl();
1428 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1429 return false;
1430 return LHS.Path == RHS.Path;
1431 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001432}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001433
Richard Smith2e312c82012-03-03 22:46:17 +00001434static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001435static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1436 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001437 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001438static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1439 bool InvalidBaseOK = false);
1440static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1441 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001442static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1443 EvalInfo &Info);
1444static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001445static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001446static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001447 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001448static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001449static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001450static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1451 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001452static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001453
1454//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001455// Misc utilities
1456//===----------------------------------------------------------------------===//
1457
Richard Smithd6cc1982017-01-31 02:23:02 +00001458/// Negate an APSInt in place, converting it to a signed form if necessary, and
1459/// preserving its value (by extending by up to one bit as needed).
1460static void negateAsSigned(APSInt &Int) {
1461 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1462 Int = Int.extend(Int.getBitWidth() + 1);
1463 Int.setIsSigned(true);
1464 }
1465 Int = -Int;
1466}
1467
Richard Smith84401042013-06-03 05:03:02 +00001468/// Produce a string describing the given constexpr call.
1469static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1470 unsigned ArgIndex = 0;
1471 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1472 !isa<CXXConstructorDecl>(Frame->Callee) &&
1473 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1474
1475 if (!IsMemberCall)
1476 Out << *Frame->Callee << '(';
1477
1478 if (Frame->This && IsMemberCall) {
1479 APValue Val;
1480 Frame->This->moveInto(Val);
1481 Val.printPretty(Out, Frame->Info.Ctx,
1482 Frame->This->Designator.MostDerivedType);
1483 // FIXME: Add parens around Val if needed.
1484 Out << "->" << *Frame->Callee << '(';
1485 IsMemberCall = false;
1486 }
1487
1488 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1489 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1490 if (ArgIndex > (unsigned)IsMemberCall)
1491 Out << ", ";
1492
1493 const ParmVarDecl *Param = *I;
1494 const APValue &Arg = Frame->Arguments[ArgIndex];
1495 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1496
1497 if (ArgIndex == 0 && IsMemberCall)
1498 Out << "->" << *Frame->Callee << '(';
1499 }
1500
1501 Out << ')';
1502}
1503
Richard Smithd9f663b2013-04-22 15:31:51 +00001504/// Evaluate an expression to see if it had side-effects, and discard its
1505/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001506/// \return \c true if the caller should keep evaluating.
1507static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001508 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001509 if (!Evaluate(Scratch, Info, E))
1510 // We don't need the value, but we might have skipped a side effect here.
1511 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001512 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001513}
1514
Richard Smithd62306a2011-11-10 06:34:14 +00001515/// Should this call expression be treated as a string literal?
1516static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001517 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001518 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1519 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1520}
1521
Richard Smithce40ad62011-11-12 22:28:03 +00001522static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001523 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1524 // constant expression of pointer type that evaluates to...
1525
1526 // ... a null pointer value, or a prvalue core constant expression of type
1527 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001528 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001529
Richard Smithce40ad62011-11-12 22:28:03 +00001530 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1531 // ... the address of an object with static storage duration,
1532 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1533 return VD->hasGlobalStorage();
1534 // ... the address of a function,
1535 return isa<FunctionDecl>(D);
1536 }
1537
1538 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001539 switch (E->getStmtClass()) {
1540 default:
1541 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001542 case Expr::CompoundLiteralExprClass: {
1543 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1544 return CLE->isFileScope() && CLE->isLValue();
1545 }
Richard Smithe6c01442013-06-05 00:46:14 +00001546 case Expr::MaterializeTemporaryExprClass:
1547 // A materialized temporary might have been lifetime-extended to static
1548 // storage duration.
1549 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001550 // A string literal has static storage duration.
1551 case Expr::StringLiteralClass:
1552 case Expr::PredefinedExprClass:
1553 case Expr::ObjCStringLiteralClass:
1554 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001555 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001556 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001557 return true;
1558 case Expr::CallExprClass:
1559 return IsStringLiteralCall(cast<CallExpr>(E));
1560 // For GCC compatibility, &&label has static storage duration.
1561 case Expr::AddrLabelExprClass:
1562 return true;
1563 // A Block literal expression may be used as the initialization value for
1564 // Block variables at global or local static scope.
1565 case Expr::BlockExprClass:
1566 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001567 case Expr::ImplicitValueInitExprClass:
1568 // FIXME:
1569 // We can never form an lvalue with an implicit value initialization as its
1570 // base through expression evaluation, so these only appear in one case: the
1571 // implicit variable declaration we invent when checking whether a constexpr
1572 // constructor can produce a constant expression. We must assume that such
1573 // an expression might be a global lvalue.
1574 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001575 }
John McCall95007602010-05-10 23:27:23 +00001576}
1577
Richard Smithb228a862012-02-15 02:18:13 +00001578static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1579 assert(Base && "no location for a null lvalue");
1580 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1581 if (VD)
1582 Info.Note(VD->getLocation(), diag::note_declared_at);
1583 else
Ted Kremenek28831752012-08-23 20:46:57 +00001584 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001585 diag::note_constexpr_temporary_here);
1586}
1587
Richard Smith80815602011-11-07 05:07:52 +00001588/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001589/// value for an address or reference constant expression. Return true if we
1590/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001591static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1592 QualType Type, const LValue &LVal) {
1593 bool IsReferenceType = Type->isReferenceType();
1594
Richard Smith357362d2011-12-13 06:39:58 +00001595 APValue::LValueBase Base = LVal.getLValueBase();
1596 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1597
Richard Smith0dea49e2012-02-18 04:58:18 +00001598 // Check that the object is a global. Note that the fake 'this' object we
1599 // manufacture when checking potential constant expressions is conservatively
1600 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001601 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001602 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001603 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001604 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001605 << IsReferenceType << !Designator.Entries.empty()
1606 << !!VD << VD;
1607 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001608 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001609 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001610 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001611 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001612 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001613 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001614 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001615 LVal.getLValueCallIndex() == 0) &&
1616 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001617
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001618 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1619 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001620 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001621 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001622 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001623
Hans Wennborg82dd8772014-06-25 22:19:48 +00001624 // A dllimport variable never acts like a constant.
1625 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001626 return false;
1627 }
1628 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1629 // __declspec(dllimport) must be handled very carefully:
1630 // We must never initialize an expression with the thunk in C++.
1631 // Doing otherwise would allow the same id-expression to yield
1632 // different addresses for the same function in different translation
1633 // units. However, this means that we must dynamically initialize the
1634 // expression with the contents of the import address table at runtime.
1635 //
1636 // The C language has no notion of ODR; furthermore, it has no notion of
1637 // dynamic initialization. This means that we are permitted to
1638 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001639 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001640 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001641 }
1642 }
1643
Richard Smitha8105bc2012-01-06 16:39:00 +00001644 // Allow address constant expressions to be past-the-end pointers. This is
1645 // an extension: the standard requires them to point to an object.
1646 if (!IsReferenceType)
1647 return true;
1648
1649 // A reference constant expression must refer to an object.
1650 if (!Base) {
1651 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001652 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001653 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001654 }
1655
Richard Smith357362d2011-12-13 06:39:58 +00001656 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001657 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001658 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001659 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001660 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001661 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001662 }
1663
Richard Smith80815602011-11-07 05:07:52 +00001664 return true;
1665}
1666
Richard Smithfddd3842011-12-30 21:15:51 +00001667/// Check that this core constant expression is of literal type, and if not,
1668/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001669static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001670 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001671 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001672 return true;
1673
Richard Smith7525ff62013-05-09 07:14:00 +00001674 // C++1y: A constant initializer for an object o [...] may also invoke
1675 // constexpr constructors for o and its subobjects even if those objects
1676 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001677 //
1678 // C++11 missed this detail for aggregates, so classes like this:
1679 // struct foo_t { union { int i; volatile int j; } u; };
1680 // are not (obviously) initializable like so:
1681 // __attribute__((__require_constant_initialization__))
1682 // static const foo_t x = {{0}};
1683 // because "i" is a subobject with non-literal initialization (due to the
1684 // volatile member of the union). See:
1685 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1686 // Therefore, we use the C++1y behavior.
1687 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001688 return true;
1689
Richard Smithfddd3842011-12-30 21:15:51 +00001690 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001691 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001692 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001693 << E->getType();
1694 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001695 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001696 return false;
1697}
1698
Richard Smith0b0a0b62011-10-29 20:57:55 +00001699/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001700/// constant expression. If not, report an appropriate diagnostic. Does not
1701/// check that the expression is of literal type.
1702static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1703 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001704 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001705 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001706 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001707 return false;
1708 }
1709
Richard Smith77be48a2014-07-31 06:31:19 +00001710 // We allow _Atomic(T) to be initialized from anything that T can be
1711 // initialized from.
1712 if (const AtomicType *AT = Type->getAs<AtomicType>())
1713 Type = AT->getValueType();
1714
Richard Smithb228a862012-02-15 02:18:13 +00001715 // Core issue 1454: For a literal constant expression of array or class type,
1716 // each subobject of its value shall have been initialized by a constant
1717 // expression.
1718 if (Value.isArray()) {
1719 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1720 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1721 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1722 Value.getArrayInitializedElt(I)))
1723 return false;
1724 }
1725 if (!Value.hasArrayFiller())
1726 return true;
1727 return CheckConstantExpression(Info, DiagLoc, EltTy,
1728 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001729 }
Richard Smithb228a862012-02-15 02:18:13 +00001730 if (Value.isUnion() && Value.getUnionField()) {
1731 return CheckConstantExpression(Info, DiagLoc,
1732 Value.getUnionField()->getType(),
1733 Value.getUnionValue());
1734 }
1735 if (Value.isStruct()) {
1736 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1737 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1738 unsigned BaseIndex = 0;
1739 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1740 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1741 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1742 Value.getStructBase(BaseIndex)))
1743 return false;
1744 }
1745 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001746 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001747 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1748 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001749 return false;
1750 }
1751 }
1752
1753 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001754 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001755 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001756 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1757 }
1758
1759 // Everything else is fine.
1760 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001761}
1762
Benjamin Kramer8407df72015-03-09 16:47:52 +00001763static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001764 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001765}
1766
1767static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001768 if (Value.CallIndex)
1769 return false;
1770 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1771 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001772}
1773
Richard Smithcecf1842011-11-01 21:06:14 +00001774static bool IsWeakLValue(const LValue &Value) {
1775 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001776 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001777}
1778
David Majnemerb5116032014-12-09 23:32:34 +00001779static bool isZeroSized(const LValue &Value) {
1780 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001781 if (Decl && isa<VarDecl>(Decl)) {
1782 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001783 if (Ty->isArrayType())
1784 return Ty->isIncompleteType() ||
1785 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001786 }
1787 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001788}
1789
Richard Smith2e312c82012-03-03 22:46:17 +00001790static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001791 // A null base expression indicates a null pointer. These are always
1792 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001793 if (!Value.getLValueBase()) {
1794 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001795 return true;
1796 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001797
Richard Smith027bf112011-11-17 22:56:20 +00001798 // We have a non-null base. These are generally known to be true, but if it's
1799 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001800 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001801 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001802 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001803}
1804
Richard Smith2e312c82012-03-03 22:46:17 +00001805static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001806 switch (Val.getKind()) {
1807 case APValue::Uninitialized:
1808 return false;
1809 case APValue::Int:
1810 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001811 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001812 case APValue::Float:
1813 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001814 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001815 case APValue::ComplexInt:
1816 Result = Val.getComplexIntReal().getBoolValue() ||
1817 Val.getComplexIntImag().getBoolValue();
1818 return true;
1819 case APValue::ComplexFloat:
1820 Result = !Val.getComplexFloatReal().isZero() ||
1821 !Val.getComplexFloatImag().isZero();
1822 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001823 case APValue::LValue:
1824 return EvalPointerValueAsBool(Val, Result);
1825 case APValue::MemberPointer:
1826 Result = Val.getMemberPointerDecl();
1827 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001828 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001829 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001830 case APValue::Struct:
1831 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001832 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001833 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001834 }
1835
Richard Smith11562c52011-10-28 17:51:58 +00001836 llvm_unreachable("unknown APValue kind");
1837}
1838
1839static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1840 EvalInfo &Info) {
1841 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001842 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001843 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001844 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001845 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001846}
1847
Richard Smith357362d2011-12-13 06:39:58 +00001848template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001849static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001850 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001851 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001852 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001853 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001854}
1855
1856static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1857 QualType SrcType, const APFloat &Value,
1858 QualType DestType, APSInt &Result) {
1859 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001860 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001861 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001862
Richard Smith357362d2011-12-13 06:39:58 +00001863 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001864 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001865 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1866 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001867 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001868 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001869}
1870
Richard Smith357362d2011-12-13 06:39:58 +00001871static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1872 QualType SrcType, QualType DestType,
1873 APFloat &Result) {
1874 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001875 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001876 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1877 APFloat::rmNearestTiesToEven, &ignored)
1878 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001879 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001880 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001881}
1882
Richard Smith911e1422012-01-30 22:27:01 +00001883static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1884 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001885 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001886 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001887 APSInt Result = Value;
1888 // Figure out if this is a truncate, extend or noop cast.
1889 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001890 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001891 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001892 return Result;
1893}
1894
Richard Smith357362d2011-12-13 06:39:58 +00001895static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1896 QualType SrcType, const APSInt &Value,
1897 QualType DestType, APFloat &Result) {
1898 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1899 if (Result.convertFromAPInt(Value, Value.isSigned(),
1900 APFloat::rmNearestTiesToEven)
1901 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001902 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001903 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001904}
1905
Richard Smith49ca8aa2013-08-06 07:09:20 +00001906static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1907 APValue &Value, const FieldDecl *FD) {
1908 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1909
1910 if (!Value.isInt()) {
1911 // Trying to store a pointer-cast-to-integer into a bitfield.
1912 // FIXME: In this case, we should provide the diagnostic for casting
1913 // a pointer to an integer.
1914 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001915 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001916 return false;
1917 }
1918
1919 APSInt &Int = Value.getInt();
1920 unsigned OldBitWidth = Int.getBitWidth();
1921 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1922 if (NewBitWidth < OldBitWidth)
1923 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1924 return true;
1925}
1926
Eli Friedman803acb32011-12-22 03:51:45 +00001927static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1928 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001929 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001930 if (!Evaluate(SVal, Info, E))
1931 return false;
1932 if (SVal.isInt()) {
1933 Res = SVal.getInt();
1934 return true;
1935 }
1936 if (SVal.isFloat()) {
1937 Res = SVal.getFloat().bitcastToAPInt();
1938 return true;
1939 }
1940 if (SVal.isVector()) {
1941 QualType VecTy = E->getType();
1942 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1943 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1944 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1945 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1946 Res = llvm::APInt::getNullValue(VecSize);
1947 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1948 APValue &Elt = SVal.getVectorElt(i);
1949 llvm::APInt EltAsInt;
1950 if (Elt.isInt()) {
1951 EltAsInt = Elt.getInt();
1952 } else if (Elt.isFloat()) {
1953 EltAsInt = Elt.getFloat().bitcastToAPInt();
1954 } else {
1955 // Don't try to handle vectors of anything other than int or float
1956 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001957 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001958 return false;
1959 }
1960 unsigned BaseEltSize = EltAsInt.getBitWidth();
1961 if (BigEndian)
1962 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1963 else
1964 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1965 }
1966 return true;
1967 }
1968 // Give up if the input isn't an int, float, or vector. For example, we
1969 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001970 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001971 return false;
1972}
1973
Richard Smith43e77732013-05-07 04:50:00 +00001974/// Perform the given integer operation, which is known to need at most BitWidth
1975/// bits, and check for overflow in the original type (if that type was not an
1976/// unsigned type).
1977template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001978static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1979 const APSInt &LHS, const APSInt &RHS,
1980 unsigned BitWidth, Operation Op,
1981 APSInt &Result) {
1982 if (LHS.isUnsigned()) {
1983 Result = Op(LHS, RHS);
1984 return true;
1985 }
Richard Smith43e77732013-05-07 04:50:00 +00001986
1987 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001988 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001989 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001990 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001991 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001992 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001993 << Result.toString(10) << E->getType();
1994 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001995 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001996 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001997 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001998}
1999
2000/// Perform the given binary integer operation.
2001static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2002 BinaryOperatorKind Opcode, APSInt RHS,
2003 APSInt &Result) {
2004 switch (Opcode) {
2005 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002006 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002007 return false;
2008 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002009 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2010 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002011 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002012 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2013 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002014 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002015 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2016 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002017 case BO_And: Result = LHS & RHS; return true;
2018 case BO_Xor: Result = LHS ^ RHS; return true;
2019 case BO_Or: Result = LHS | RHS; return true;
2020 case BO_Div:
2021 case BO_Rem:
2022 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002023 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002024 return false;
2025 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002026 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2027 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2028 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002029 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2030 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002031 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2032 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002033 return true;
2034 case BO_Shl: {
2035 if (Info.getLangOpts().OpenCL)
2036 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2037 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2038 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2039 RHS.isUnsigned());
2040 else if (RHS.isSigned() && RHS.isNegative()) {
2041 // During constant-folding, a negative shift is an opposite shift. Such
2042 // a shift is not a constant expression.
2043 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2044 RHS = -RHS;
2045 goto shift_right;
2046 }
2047 shift_left:
2048 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2049 // the shifted type.
2050 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2051 if (SA != RHS) {
2052 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2053 << RHS << E->getType() << LHS.getBitWidth();
2054 } else if (LHS.isSigned()) {
2055 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2056 // operand, and must not overflow the corresponding unsigned type.
2057 if (LHS.isNegative())
2058 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2059 else if (LHS.countLeadingZeros() < SA)
2060 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2061 }
2062 Result = LHS << SA;
2063 return true;
2064 }
2065 case BO_Shr: {
2066 if (Info.getLangOpts().OpenCL)
2067 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2068 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2069 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2070 RHS.isUnsigned());
2071 else if (RHS.isSigned() && RHS.isNegative()) {
2072 // During constant-folding, a negative shift is an opposite shift. Such a
2073 // shift is not a constant expression.
2074 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2075 RHS = -RHS;
2076 goto shift_left;
2077 }
2078 shift_right:
2079 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2080 // shifted type.
2081 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2082 if (SA != RHS)
2083 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2084 << RHS << E->getType() << LHS.getBitWidth();
2085 Result = LHS >> SA;
2086 return true;
2087 }
2088
2089 case BO_LT: Result = LHS < RHS; return true;
2090 case BO_GT: Result = LHS > RHS; return true;
2091 case BO_LE: Result = LHS <= RHS; return true;
2092 case BO_GE: Result = LHS >= RHS; return true;
2093 case BO_EQ: Result = LHS == RHS; return true;
2094 case BO_NE: Result = LHS != RHS; return true;
2095 }
2096}
2097
Richard Smith861b5b52013-05-07 23:34:45 +00002098/// Perform the given binary floating-point operation, in-place, on LHS.
2099static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2100 APFloat &LHS, BinaryOperatorKind Opcode,
2101 const APFloat &RHS) {
2102 switch (Opcode) {
2103 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002104 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002105 return false;
2106 case BO_Mul:
2107 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2108 break;
2109 case BO_Add:
2110 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2111 break;
2112 case BO_Sub:
2113 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2114 break;
2115 case BO_Div:
2116 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2117 break;
2118 }
2119
Richard Smith0c6124b2015-12-03 01:36:22 +00002120 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002121 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002122 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002123 }
Richard Smith861b5b52013-05-07 23:34:45 +00002124 return true;
2125}
2126
Richard Smitha8105bc2012-01-06 16:39:00 +00002127/// Cast an lvalue referring to a base subobject to a derived class, by
2128/// truncating the lvalue's path to the given length.
2129static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2130 const RecordDecl *TruncatedType,
2131 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002132 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002133
2134 // Check we actually point to a derived class object.
2135 if (TruncatedElements == D.Entries.size())
2136 return true;
2137 assert(TruncatedElements >= D.MostDerivedPathLength &&
2138 "not casting to a derived class");
2139 if (!Result.checkSubobject(Info, E, CSK_Derived))
2140 return false;
2141
2142 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002143 const RecordDecl *RD = TruncatedType;
2144 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002145 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002146 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2147 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002148 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002149 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002150 else
Richard Smithd62306a2011-11-10 06:34:14 +00002151 Result.Offset -= Layout.getBaseClassOffset(Base);
2152 RD = Base;
2153 }
Richard Smith027bf112011-11-17 22:56:20 +00002154 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002155 return true;
2156}
2157
John McCalld7bca762012-05-01 00:38:49 +00002158static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002159 const CXXRecordDecl *Derived,
2160 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002161 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002162 if (!RL) {
2163 if (Derived->isInvalidDecl()) return false;
2164 RL = &Info.Ctx.getASTRecordLayout(Derived);
2165 }
2166
Richard Smithd62306a2011-11-10 06:34:14 +00002167 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002168 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002169 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002170}
2171
Richard Smitha8105bc2012-01-06 16:39:00 +00002172static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002173 const CXXRecordDecl *DerivedDecl,
2174 const CXXBaseSpecifier *Base) {
2175 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2176
John McCalld7bca762012-05-01 00:38:49 +00002177 if (!Base->isVirtual())
2178 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002179
Richard Smitha8105bc2012-01-06 16:39:00 +00002180 SubobjectDesignator &D = Obj.Designator;
2181 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002182 return false;
2183
Richard Smitha8105bc2012-01-06 16:39:00 +00002184 // Extract most-derived object and corresponding type.
2185 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2186 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2187 return false;
2188
2189 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002190 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002191 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2192 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002193 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002194 return true;
2195}
2196
Richard Smith84401042013-06-03 05:03:02 +00002197static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2198 QualType Type, LValue &Result) {
2199 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2200 PathE = E->path_end();
2201 PathI != PathE; ++PathI) {
2202 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2203 *PathI))
2204 return false;
2205 Type = (*PathI)->getType();
2206 }
2207 return true;
2208}
2209
Richard Smithd62306a2011-11-10 06:34:14 +00002210/// Update LVal to refer to the given field, which must be a member of the type
2211/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002212static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002213 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002214 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002215 if (!RL) {
2216 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002217 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002218 }
Richard Smithd62306a2011-11-10 06:34:14 +00002219
2220 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002221 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002222 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002223 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002224}
2225
Richard Smith1b78b3d2012-01-25 22:15:11 +00002226/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002227static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002228 LValue &LVal,
2229 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002230 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002231 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002232 return false;
2233 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002234}
2235
Richard Smithd62306a2011-11-10 06:34:14 +00002236/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002237static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2238 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002239 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2240 // extension.
2241 if (Type->isVoidType() || Type->isFunctionType()) {
2242 Size = CharUnits::One();
2243 return true;
2244 }
2245
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002246 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002247 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002248 return false;
2249 }
2250
Richard Smithd62306a2011-11-10 06:34:14 +00002251 if (!Type->isConstantSizeType()) {
2252 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002253 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002254 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002255 return false;
2256 }
2257
2258 Size = Info.Ctx.getTypeSizeInChars(Type);
2259 return true;
2260}
2261
2262/// Update a pointer value to model pointer arithmetic.
2263/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002264/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002265/// \param LVal - The pointer value to be updated.
2266/// \param EltTy - The pointee type represented by LVal.
2267/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002268static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2269 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002270 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002271 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002272 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002273 return false;
2274
Yaxun Liu402804b2016-12-15 08:09:08 +00002275 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002276 return true;
2277}
2278
Richard Smithd6cc1982017-01-31 02:23:02 +00002279static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2280 LValue &LVal, QualType EltTy,
2281 int64_t Adjustment) {
2282 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2283 APSInt::get(Adjustment));
2284}
2285
Richard Smith66c96992012-02-18 22:04:06 +00002286/// Update an lvalue to refer to a component of a complex number.
2287/// \param Info - Information about the ongoing evaluation.
2288/// \param LVal - The lvalue to be updated.
2289/// \param EltTy - The complex number's component type.
2290/// \param Imag - False for the real component, true for the imaginary.
2291static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2292 LValue &LVal, QualType EltTy,
2293 bool Imag) {
2294 if (Imag) {
2295 CharUnits SizeOfComponent;
2296 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2297 return false;
2298 LVal.Offset += SizeOfComponent;
2299 }
2300 LVal.addComplex(Info, E, EltTy, Imag);
2301 return true;
2302}
2303
Faisal Vali051e3a22017-02-16 04:12:21 +00002304static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2305 QualType Type, const LValue &LVal,
2306 APValue &RVal);
2307
Richard Smith27908702011-10-24 17:54:18 +00002308/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002309///
2310/// \param Info Information about the ongoing evaluation.
2311/// \param E An expression to be used when printing diagnostics.
2312/// \param VD The variable whose initializer should be obtained.
2313/// \param Frame The frame in which the variable was created. Must be null
2314/// if this variable is not local to the evaluation.
2315/// \param Result Filled in with a pointer to the value of the variable.
2316static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2317 const VarDecl *VD, CallStackFrame *Frame,
2318 APValue *&Result) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002319
Richard Smith254a73d2011-10-28 22:34:42 +00002320 // If this is a parameter to an active constexpr function call, perform
2321 // argument substitution.
2322 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002323 // Assume arguments of a potential constant expression are unknown
2324 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002325 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002326 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002327 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002328 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002329 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002330 }
Richard Smith3229b742013-05-05 21:17:10 +00002331 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002332 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002333 }
Richard Smith27908702011-10-24 17:54:18 +00002334
Richard Smithd9f663b2013-04-22 15:31:51 +00002335 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002336 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002337 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002338 if (!Result) {
2339 // Assume variables referenced within a lambda's call operator that were
2340 // not declared within the call operator are captures and during checking
2341 // of a potential constant expression, assume they are unknown constant
2342 // expressions.
2343 assert(isLambdaCallOperator(Frame->Callee) &&
2344 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2345 "missing value for local variable");
2346 if (Info.checkingPotentialConstantExpression())
2347 return false;
2348 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002349 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002350 diag::note_unimplemented_constexpr_lambda_feature_ast)
2351 << "captures not currently allowed";
2352 return false;
2353 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002354 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002355 }
2356
Richard Smithd0b4dd62011-12-19 06:19:21 +00002357 // Dig out the initializer, and use the declaration which it's attached to.
2358 const Expr *Init = VD->getAnyInitializer(VD);
2359 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002360 // If we're checking a potential constant expression, the variable could be
2361 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002362 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002363 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002364 return false;
2365 }
2366
Richard Smithd62306a2011-11-10 06:34:14 +00002367 // If we're currently evaluating the initializer of this declaration, use that
2368 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002369 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002370 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002371 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002372 }
2373
Richard Smithcecf1842011-11-01 21:06:14 +00002374 // Never evaluate the initializer of a weak variable. We can't be sure that
2375 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002376 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002377 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002378 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002379 }
Richard Smithcecf1842011-11-01 21:06:14 +00002380
Richard Smithd0b4dd62011-12-19 06:19:21 +00002381 // Check that we can fold the initializer. In C++, we will have already done
2382 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002383 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002384 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002385 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002386 Notes.size() + 1) << VD;
2387 Info.Note(VD->getLocation(), diag::note_declared_at);
2388 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002389 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002390 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002391 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002392 Notes.size() + 1) << VD;
2393 Info.Note(VD->getLocation(), diag::note_declared_at);
2394 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002395 }
Richard Smith27908702011-10-24 17:54:18 +00002396
Richard Smith3229b742013-05-05 21:17:10 +00002397 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002398 return true;
Richard Smith27908702011-10-24 17:54:18 +00002399}
2400
Richard Smith11562c52011-10-28 17:51:58 +00002401static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002402 Qualifiers Quals = T.getQualifiers();
2403 return Quals.hasConst() && !Quals.hasVolatile();
2404}
2405
Richard Smithe97cbd72011-11-11 04:05:33 +00002406/// Get the base index of the given base class within an APValue representing
2407/// the given derived class.
2408static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2409 const CXXRecordDecl *Base) {
2410 Base = Base->getCanonicalDecl();
2411 unsigned Index = 0;
2412 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2413 E = Derived->bases_end(); I != E; ++I, ++Index) {
2414 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2415 return Index;
2416 }
2417
2418 llvm_unreachable("base class missing from derived class's bases list");
2419}
2420
Richard Smith3da88fa2013-04-26 14:36:30 +00002421/// Extract the value of a character from a string literal.
2422static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2423 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002424 // FIXME: Support MakeStringConstant
2425 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2426 std::string Str;
2427 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2428 assert(Index <= Str.size() && "Index too large");
2429 return APSInt::getUnsigned(Str.c_str()[Index]);
2430 }
2431
Alexey Bataevec474782014-10-09 08:45:04 +00002432 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2433 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002434 const StringLiteral *S = cast<StringLiteral>(Lit);
2435 const ConstantArrayType *CAT =
2436 Info.Ctx.getAsConstantArrayType(S->getType());
2437 assert(CAT && "string literal isn't an array");
2438 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002439 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002440
2441 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002442 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002443 if (Index < S->getLength())
2444 Value = S->getCodeUnit(Index);
2445 return Value;
2446}
2447
Richard Smith3da88fa2013-04-26 14:36:30 +00002448// Expand a string literal into an array of characters.
2449static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2450 APValue &Result) {
2451 const StringLiteral *S = cast<StringLiteral>(Lit);
2452 const ConstantArrayType *CAT =
2453 Info.Ctx.getAsConstantArrayType(S->getType());
2454 assert(CAT && "string literal isn't an array");
2455 QualType CharType = CAT->getElementType();
2456 assert(CharType->isIntegerType() && "unexpected character type");
2457
2458 unsigned Elts = CAT->getSize().getZExtValue();
2459 Result = APValue(APValue::UninitArray(),
2460 std::min(S->getLength(), Elts), Elts);
2461 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2462 CharType->isUnsignedIntegerType());
2463 if (Result.hasArrayFiller())
2464 Result.getArrayFiller() = APValue(Value);
2465 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2466 Value = S->getCodeUnit(I);
2467 Result.getArrayInitializedElt(I) = APValue(Value);
2468 }
2469}
2470
2471// Expand an array so that it has more than Index filled elements.
2472static void expandArray(APValue &Array, unsigned Index) {
2473 unsigned Size = Array.getArraySize();
2474 assert(Index < Size);
2475
2476 // Always at least double the number of elements for which we store a value.
2477 unsigned OldElts = Array.getArrayInitializedElts();
2478 unsigned NewElts = std::max(Index+1, OldElts * 2);
2479 NewElts = std::min(Size, std::max(NewElts, 8u));
2480
2481 // Copy the data across.
2482 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2483 for (unsigned I = 0; I != OldElts; ++I)
2484 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2485 for (unsigned I = OldElts; I != NewElts; ++I)
2486 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2487 if (NewValue.hasArrayFiller())
2488 NewValue.getArrayFiller() = Array.getArrayFiller();
2489 Array.swap(NewValue);
2490}
2491
Richard Smithb01fe402014-09-16 01:24:02 +00002492/// Determine whether a type would actually be read by an lvalue-to-rvalue
2493/// conversion. If it's of class type, we may assume that the copy operation
2494/// is trivial. Note that this is never true for a union type with fields
2495/// (because the copy always "reads" the active member) and always true for
2496/// a non-class type.
2497static bool isReadByLvalueToRvalueConversion(QualType T) {
2498 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2499 if (!RD || (RD->isUnion() && !RD->field_empty()))
2500 return true;
2501 if (RD->isEmpty())
2502 return false;
2503
2504 for (auto *Field : RD->fields())
2505 if (isReadByLvalueToRvalueConversion(Field->getType()))
2506 return true;
2507
2508 for (auto &BaseSpec : RD->bases())
2509 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2510 return true;
2511
2512 return false;
2513}
2514
2515/// Diagnose an attempt to read from any unreadable field within the specified
2516/// type, which might be a class type.
2517static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2518 QualType T) {
2519 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2520 if (!RD)
2521 return false;
2522
2523 if (!RD->hasMutableFields())
2524 return false;
2525
2526 for (auto *Field : RD->fields()) {
2527 // If we're actually going to read this field in some way, then it can't
2528 // be mutable. If we're in a union, then assigning to a mutable field
2529 // (even an empty one) can change the active member, so that's not OK.
2530 // FIXME: Add core issue number for the union case.
2531 if (Field->isMutable() &&
2532 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002533 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002534 Info.Note(Field->getLocation(), diag::note_declared_at);
2535 return true;
2536 }
2537
2538 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2539 return true;
2540 }
2541
2542 for (auto &BaseSpec : RD->bases())
2543 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2544 return true;
2545
2546 // All mutable fields were empty, and thus not actually read.
2547 return false;
2548}
2549
Richard Smith861b5b52013-05-07 23:34:45 +00002550/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002551enum AccessKinds {
2552 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002553 AK_Assign,
2554 AK_Increment,
2555 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002556};
2557
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002558namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002559/// A handle to a complete object (an object that is not a subobject of
2560/// another object).
2561struct CompleteObject {
2562 /// The value of the complete object.
2563 APValue *Value;
2564 /// The type of the complete object.
2565 QualType Type;
2566
Craig Topper36250ad2014-05-12 05:36:57 +00002567 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002568 CompleteObject(APValue *Value, QualType Type)
2569 : Value(Value), Type(Type) {
2570 assert(Value && "missing value for complete object");
2571 }
2572
Aaron Ballman67347662015-02-15 22:00:28 +00002573 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002574};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002575} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002576
Richard Smith3da88fa2013-04-26 14:36:30 +00002577/// Find the designated sub-object of an rvalue.
2578template<typename SubobjectHandler>
2579typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002580findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002581 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002582 if (Sub.Invalid)
2583 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002584 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002585 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002586 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002587 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002588 << handler.AccessKind;
2589 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002590 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002591 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002592 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002593
Richard Smith3229b742013-05-05 21:17:10 +00002594 APValue *O = Obj.Value;
2595 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002596 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002597
Richard Smithd62306a2011-11-10 06:34:14 +00002598 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002599 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2600 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002601 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002602 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002603 return handler.failed();
2604 }
2605
Richard Smith49ca8aa2013-08-06 07:09:20 +00002606 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002607 // If we are reading an object of class type, there may still be more
2608 // things we need to check: if there are any mutable subobjects, we
2609 // cannot perform this read. (This only happens when performing a trivial
2610 // copy or assignment.)
2611 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2612 diagnoseUnreadableFields(Info, E, ObjType))
2613 return handler.failed();
2614
Richard Smith49ca8aa2013-08-06 07:09:20 +00002615 if (!handler.found(*O, ObjType))
2616 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002617
Richard Smith49ca8aa2013-08-06 07:09:20 +00002618 // If we modified a bit-field, truncate it to the right width.
2619 if (handler.AccessKind != AK_Read &&
2620 LastField && LastField->isBitField() &&
2621 !truncateBitfieldValue(Info, E, *O, LastField))
2622 return false;
2623
2624 return true;
2625 }
2626
Craig Topper36250ad2014-05-12 05:36:57 +00002627 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002628 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002629 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002630 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002631 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002632 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002633 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002634 // Note, it should not be possible to form a pointer with a valid
2635 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002636 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002637 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002638 << handler.AccessKind;
2639 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002640 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002641 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002642 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002643
2644 ObjType = CAT->getElementType();
2645
Richard Smith14a94132012-02-17 03:35:37 +00002646 // An array object is represented as either an Array APValue or as an
2647 // LValue which refers to a string literal.
2648 if (O->isLValue()) {
2649 assert(I == N - 1 && "extracting subobject of character?");
2650 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002651 if (handler.AccessKind != AK_Read)
2652 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2653 *O);
2654 else
2655 return handler.foundString(*O, ObjType, Index);
2656 }
2657
2658 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002659 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002660 else if (handler.AccessKind != AK_Read) {
2661 expandArray(*O, Index);
2662 O = &O->getArrayInitializedElt(Index);
2663 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002664 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002665 } else if (ObjType->isAnyComplexType()) {
2666 // Next subobject is a complex number.
2667 uint64_t Index = Sub.Entries[I].ArrayIndex;
2668 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002669 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002670 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002671 << handler.AccessKind;
2672 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002673 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002674 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002675 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002676
2677 bool WasConstQualified = ObjType.isConstQualified();
2678 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2679 if (WasConstQualified)
2680 ObjType.addConst();
2681
Richard Smith66c96992012-02-18 22:04:06 +00002682 assert(I == N - 1 && "extracting subobject of scalar?");
2683 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002684 return handler.found(Index ? O->getComplexIntImag()
2685 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002686 } else {
2687 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002688 return handler.found(Index ? O->getComplexFloatImag()
2689 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002690 }
Richard Smithd62306a2011-11-10 06:34:14 +00002691 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002692 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002693 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002694 << Field;
2695 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002696 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002697 }
2698
Richard Smithd62306a2011-11-10 06:34:14 +00002699 // Next subobject is a class, struct or union field.
2700 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2701 if (RD->isUnion()) {
2702 const FieldDecl *UnionField = O->getUnionField();
2703 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002704 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002705 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002706 << handler.AccessKind << Field << !UnionField << UnionField;
2707 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002708 }
Richard Smithd62306a2011-11-10 06:34:14 +00002709 O = &O->getUnionValue();
2710 } else
2711 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002712
2713 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002714 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002715 if (WasConstQualified && !Field->isMutable())
2716 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002717
2718 if (ObjType.isVolatileQualified()) {
2719 if (Info.getLangOpts().CPlusPlus) {
2720 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002721 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002722 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002723 Info.Note(Field->getLocation(), diag::note_declared_at);
2724 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002725 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002726 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002727 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002728 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002729
2730 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002731 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002732 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002733 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2734 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2735 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002736
2737 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002738 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002739 if (WasConstQualified)
2740 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002741 }
2742 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002743}
2744
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002745namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002746struct ExtractSubobjectHandler {
2747 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002748 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002749
2750 static const AccessKinds AccessKind = AK_Read;
2751
2752 typedef bool result_type;
2753 bool failed() { return false; }
2754 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002755 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002756 return true;
2757 }
2758 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002759 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002760 return true;
2761 }
2762 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002763 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002764 return true;
2765 }
2766 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002767 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002768 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2769 return true;
2770 }
2771};
Richard Smith3229b742013-05-05 21:17:10 +00002772} // end anonymous namespace
2773
Richard Smith3da88fa2013-04-26 14:36:30 +00002774const AccessKinds ExtractSubobjectHandler::AccessKind;
2775
2776/// Extract the designated sub-object of an rvalue.
2777static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002778 const CompleteObject &Obj,
2779 const SubobjectDesignator &Sub,
2780 APValue &Result) {
2781 ExtractSubobjectHandler Handler = { Info, Result };
2782 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002783}
2784
Richard Smith3229b742013-05-05 21:17:10 +00002785namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002786struct ModifySubobjectHandler {
2787 EvalInfo &Info;
2788 APValue &NewVal;
2789 const Expr *E;
2790
2791 typedef bool result_type;
2792 static const AccessKinds AccessKind = AK_Assign;
2793
2794 bool checkConst(QualType QT) {
2795 // Assigning to a const object has undefined behavior.
2796 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002797 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002798 return false;
2799 }
2800 return true;
2801 }
2802
2803 bool failed() { return false; }
2804 bool found(APValue &Subobj, QualType SubobjType) {
2805 if (!checkConst(SubobjType))
2806 return false;
2807 // We've been given ownership of NewVal, so just swap it in.
2808 Subobj.swap(NewVal);
2809 return true;
2810 }
2811 bool found(APSInt &Value, QualType SubobjType) {
2812 if (!checkConst(SubobjType))
2813 return false;
2814 if (!NewVal.isInt()) {
2815 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002816 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002817 return false;
2818 }
2819 Value = NewVal.getInt();
2820 return true;
2821 }
2822 bool found(APFloat &Value, QualType SubobjType) {
2823 if (!checkConst(SubobjType))
2824 return false;
2825 Value = NewVal.getFloat();
2826 return true;
2827 }
2828 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2829 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2830 }
2831};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002832} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002833
Richard Smith3229b742013-05-05 21:17:10 +00002834const AccessKinds ModifySubobjectHandler::AccessKind;
2835
Richard Smith3da88fa2013-04-26 14:36:30 +00002836/// Update the designated sub-object of an rvalue to the given value.
2837static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002838 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002839 const SubobjectDesignator &Sub,
2840 APValue &NewVal) {
2841 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002842 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002843}
2844
Richard Smith84f6dcf2012-02-02 01:16:57 +00002845/// Find the position where two subobject designators diverge, or equivalently
2846/// the length of the common initial subsequence.
2847static unsigned FindDesignatorMismatch(QualType ObjType,
2848 const SubobjectDesignator &A,
2849 const SubobjectDesignator &B,
2850 bool &WasArrayIndex) {
2851 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2852 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002853 if (!ObjType.isNull() &&
2854 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002855 // Next subobject is an array element.
2856 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2857 WasArrayIndex = true;
2858 return I;
2859 }
Richard Smith66c96992012-02-18 22:04:06 +00002860 if (ObjType->isAnyComplexType())
2861 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2862 else
2863 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002864 } else {
2865 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2866 WasArrayIndex = false;
2867 return I;
2868 }
2869 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2870 // Next subobject is a field.
2871 ObjType = FD->getType();
2872 else
2873 // Next subobject is a base class.
2874 ObjType = QualType();
2875 }
2876 }
2877 WasArrayIndex = false;
2878 return I;
2879}
2880
2881/// Determine whether the given subobject designators refer to elements of the
2882/// same array object.
2883static bool AreElementsOfSameArray(QualType ObjType,
2884 const SubobjectDesignator &A,
2885 const SubobjectDesignator &B) {
2886 if (A.Entries.size() != B.Entries.size())
2887 return false;
2888
George Burgess IVa51c4072015-10-16 01:49:01 +00002889 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002890 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2891 // A is a subobject of the array element.
2892 return false;
2893
2894 // If A (and B) designates an array element, the last entry will be the array
2895 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2896 // of length 1' case, and the entire path must match.
2897 bool WasArrayIndex;
2898 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2899 return CommonLength >= A.Entries.size() - IsArray;
2900}
2901
Richard Smith3229b742013-05-05 21:17:10 +00002902/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002903static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2904 AccessKinds AK, const LValue &LVal,
2905 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002906 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002907 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002908 return CompleteObject();
2909 }
2910
Craig Topper36250ad2014-05-12 05:36:57 +00002911 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002912 if (LVal.CallIndex) {
2913 Frame = Info.getCallFrame(LVal.CallIndex);
2914 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002915 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002916 << AK << LVal.Base.is<const ValueDecl*>();
2917 NoteLValueLocation(Info, LVal.Base);
2918 return CompleteObject();
2919 }
Richard Smith3229b742013-05-05 21:17:10 +00002920 }
2921
2922 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2923 // is not a constant expression (even if the object is non-volatile). We also
2924 // apply this rule to C++98, in order to conform to the expected 'volatile'
2925 // semantics.
2926 if (LValType.isVolatileQualified()) {
2927 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002928 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002929 << AK << LValType;
2930 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002931 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002932 return CompleteObject();
2933 }
2934
2935 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002936 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002937 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002938
2939 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2940 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2941 // In C++11, constexpr, non-volatile variables initialized with constant
2942 // expressions are constant expressions too. Inside constexpr functions,
2943 // parameters are constant expressions even if they're non-const.
2944 // In C++1y, objects local to a constant expression (those with a Frame) are
2945 // both readable and writable inside constant expressions.
2946 // In C, such things can also be folded, although they are not ICEs.
2947 const VarDecl *VD = dyn_cast<VarDecl>(D);
2948 if (VD) {
2949 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2950 VD = VDef;
2951 }
2952 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002953 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002954 return CompleteObject();
2955 }
2956
2957 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002958 if (BaseType.isVolatileQualified()) {
2959 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002960 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002961 << AK << 1 << VD;
2962 Info.Note(VD->getLocation(), diag::note_declared_at);
2963 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002964 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002965 }
2966 return CompleteObject();
2967 }
2968
2969 // Unless we're looking at a local variable or argument in a constexpr call,
2970 // the variable we're reading must be const.
2971 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002972 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002973 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2974 // OK, we can read and modify an object if we're in the process of
2975 // evaluating its initializer, because its lifetime began in this
2976 // evaluation.
2977 } else if (AK != AK_Read) {
2978 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002979 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002980 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00002981 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002982 // OK, we can read this variable.
2983 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002984 // In OpenCL if a variable is in constant address space it is a const value.
2985 if (!(BaseType.isConstQualified() ||
2986 (Info.getLangOpts().OpenCL &&
2987 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002988 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002989 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002990 Info.Note(VD->getLocation(), diag::note_declared_at);
2991 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002992 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002993 }
2994 return CompleteObject();
2995 }
2996 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2997 // We support folding of const floating-point types, in order to make
2998 // static const data members of such types (supported as an extension)
2999 // more useful.
3000 if (Info.getLangOpts().CPlusPlus11) {
3001 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3002 Info.Note(VD->getLocation(), diag::note_declared_at);
3003 } else {
3004 Info.CCEDiag(E);
3005 }
George Burgess IVb5316982016-12-27 05:33:20 +00003006 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3007 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3008 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003009 } else {
3010 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003011 if (Info.checkingPotentialConstantExpression() &&
3012 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3013 // The definition of this variable could be constexpr. We can't
3014 // access it right now, but may be able to in future.
3015 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003016 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003017 Info.Note(VD->getLocation(), diag::note_declared_at);
3018 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003019 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003020 }
3021 return CompleteObject();
3022 }
3023 }
3024
3025 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3026 return CompleteObject();
3027 } else {
3028 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3029
3030 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003031 if (const MaterializeTemporaryExpr *MTE =
3032 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3033 assert(MTE->getStorageDuration() == SD_Static &&
3034 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003035
Richard Smithe6c01442013-06-05 00:46:14 +00003036 // Per C++1y [expr.const]p2:
3037 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3038 // - a [...] glvalue of integral or enumeration type that refers to
3039 // a non-volatile const object [...]
3040 // [...]
3041 // - a [...] glvalue of literal type that refers to a non-volatile
3042 // object whose lifetime began within the evaluation of e.
3043 //
3044 // C++11 misses the 'began within the evaluation of e' check and
3045 // instead allows all temporaries, including things like:
3046 // int &&r = 1;
3047 // int x = ++r;
3048 // constexpr int k = r;
3049 // Therefore we use the C++1y rules in C++11 too.
3050 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3051 const ValueDecl *ED = MTE->getExtendingDecl();
3052 if (!(BaseType.isConstQualified() &&
3053 BaseType->isIntegralOrEnumerationType()) &&
3054 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003055 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003056 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3057 return CompleteObject();
3058 }
3059
3060 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3061 assert(BaseVal && "got reference to unevaluated temporary");
3062 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003063 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003064 return CompleteObject();
3065 }
3066 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003067 BaseVal = Frame->getTemporary(Base);
3068 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003069 }
Richard Smith3229b742013-05-05 21:17:10 +00003070
3071 // Volatile temporary objects cannot be accessed in constant expressions.
3072 if (BaseType.isVolatileQualified()) {
3073 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003074 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003075 << AK << 0;
3076 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3077 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003078 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003079 }
3080 return CompleteObject();
3081 }
3082 }
3083
Richard Smith7525ff62013-05-09 07:14:00 +00003084 // During the construction of an object, it is not yet 'const'.
3085 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3086 // and this doesn't do quite the right thing for const subobjects of the
3087 // object under construction.
3088 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3089 BaseType = Info.Ctx.getCanonicalType(BaseType);
3090 BaseType.removeLocalConst();
3091 }
3092
Richard Smith6d4c6582013-11-05 22:18:15 +00003093 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003094 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003095 //
3096 // FIXME: Not all local state is mutable. Allow local constant subobjects
3097 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003098 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3099 Info.EvalStatus.HasSideEffects) ||
3100 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003101 return CompleteObject();
3102
3103 return CompleteObject(BaseVal, BaseType);
3104}
3105
Richard Smith243ef902013-05-05 23:31:59 +00003106/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3107/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3108/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003109///
3110/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003111/// \param Conv - The expression for which we are performing the conversion.
3112/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003113/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3114/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003115/// \param LVal - The glvalue on which we are attempting to perform this action.
3116/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003117static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003118 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003119 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003120 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003121 return false;
3122
Richard Smith3229b742013-05-05 21:17:10 +00003123 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003124 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003125 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003126 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3127 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3128 // initializer until now for such expressions. Such an expression can't be
3129 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003130 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003131 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003132 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003133 }
Richard Smith3229b742013-05-05 21:17:10 +00003134 APValue Lit;
3135 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3136 return false;
3137 CompleteObject LitObj(&Lit, Base->getType());
3138 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003139 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003140 // We represent a string literal array as an lvalue pointing at the
3141 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003142 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003143 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3144 CompleteObject StrObj(&Str, Base->getType());
3145 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003146 }
Richard Smith11562c52011-10-28 17:51:58 +00003147 }
3148
Richard Smith3229b742013-05-05 21:17:10 +00003149 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3150 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003151}
3152
3153/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003154static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003155 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003156 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003157 return false;
3158
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003159 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003160 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003161 return false;
3162 }
3163
Richard Smith3229b742013-05-05 21:17:10 +00003164 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3165 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00003166}
3167
Richard Smith243ef902013-05-05 23:31:59 +00003168static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3169 return T->isSignedIntegerType() &&
3170 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3171}
3172
3173namespace {
Richard Smith43e77732013-05-07 04:50:00 +00003174struct CompoundAssignSubobjectHandler {
3175 EvalInfo &Info;
3176 const Expr *E;
3177 QualType PromotedLHSType;
3178 BinaryOperatorKind Opcode;
3179 const APValue &RHS;
3180
3181 static const AccessKinds AccessKind = AK_Assign;
3182
3183 typedef bool result_type;
3184
3185 bool checkConst(QualType QT) {
3186 // Assigning to a const object has undefined behavior.
3187 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003188 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003189 return false;
3190 }
3191 return true;
3192 }
3193
3194 bool failed() { return false; }
3195 bool found(APValue &Subobj, QualType SubobjType) {
3196 switch (Subobj.getKind()) {
3197 case APValue::Int:
3198 return found(Subobj.getInt(), SubobjType);
3199 case APValue::Float:
3200 return found(Subobj.getFloat(), SubobjType);
3201 case APValue::ComplexInt:
3202 case APValue::ComplexFloat:
3203 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003204 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003205 return false;
3206 case APValue::LValue:
3207 return foundPointer(Subobj, SubobjType);
3208 default:
3209 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003210 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003211 return false;
3212 }
3213 }
3214 bool found(APSInt &Value, QualType SubobjType) {
3215 if (!checkConst(SubobjType))
3216 return false;
3217
3218 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3219 // We don't support compound assignment on integer-cast-to-pointer
3220 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003221 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003222 return false;
3223 }
3224
3225 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3226 SubobjType, Value);
3227 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3228 return false;
3229 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3230 return true;
3231 }
3232 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003233 return checkConst(SubobjType) &&
3234 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3235 Value) &&
3236 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3237 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003238 }
3239 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3240 if (!checkConst(SubobjType))
3241 return false;
3242
3243 QualType PointeeType;
3244 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3245 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003246
3247 if (PointeeType.isNull() || !RHS.isInt() ||
3248 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003249 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003250 return false;
3251 }
3252
Richard Smithd6cc1982017-01-31 02:23:02 +00003253 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003254 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003255 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003256
3257 LValue LVal;
3258 LVal.setFrom(Info.Ctx, Subobj);
3259 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3260 return false;
3261 LVal.moveInto(Subobj);
3262 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003263 }
3264 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3265 llvm_unreachable("shouldn't encounter string elements here");
3266 }
3267};
3268} // end anonymous namespace
3269
3270const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3271
3272/// Perform a compound assignment of LVal <op>= RVal.
3273static bool handleCompoundAssignment(
3274 EvalInfo &Info, const Expr *E,
3275 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3276 BinaryOperatorKind Opcode, const APValue &RVal) {
3277 if (LVal.Designator.Invalid)
3278 return false;
3279
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003280 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003281 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003282 return false;
3283 }
3284
3285 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3286 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3287 RVal };
3288 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3289}
3290
3291namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003292struct IncDecSubobjectHandler {
3293 EvalInfo &Info;
3294 const Expr *E;
3295 AccessKinds AccessKind;
3296 APValue *Old;
3297
3298 typedef bool result_type;
3299
3300 bool checkConst(QualType QT) {
3301 // Assigning to a const object has undefined behavior.
3302 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003303 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003304 return false;
3305 }
3306 return true;
3307 }
3308
3309 bool failed() { return false; }
3310 bool found(APValue &Subobj, QualType SubobjType) {
3311 // Stash the old value. Also clear Old, so we don't clobber it later
3312 // if we're post-incrementing a complex.
3313 if (Old) {
3314 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003315 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003316 }
3317
3318 switch (Subobj.getKind()) {
3319 case APValue::Int:
3320 return found(Subobj.getInt(), SubobjType);
3321 case APValue::Float:
3322 return found(Subobj.getFloat(), SubobjType);
3323 case APValue::ComplexInt:
3324 return found(Subobj.getComplexIntReal(),
3325 SubobjType->castAs<ComplexType>()->getElementType()
3326 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3327 case APValue::ComplexFloat:
3328 return found(Subobj.getComplexFloatReal(),
3329 SubobjType->castAs<ComplexType>()->getElementType()
3330 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3331 case APValue::LValue:
3332 return foundPointer(Subobj, SubobjType);
3333 default:
3334 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003335 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003336 return false;
3337 }
3338 }
3339 bool found(APSInt &Value, QualType SubobjType) {
3340 if (!checkConst(SubobjType))
3341 return false;
3342
3343 if (!SubobjType->isIntegerType()) {
3344 // We don't support increment / decrement on integer-cast-to-pointer
3345 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003346 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003347 return false;
3348 }
3349
3350 if (Old) *Old = APValue(Value);
3351
3352 // bool arithmetic promotes to int, and the conversion back to bool
3353 // doesn't reduce mod 2^n, so special-case it.
3354 if (SubobjType->isBooleanType()) {
3355 if (AccessKind == AK_Increment)
3356 Value = 1;
3357 else
3358 Value = !Value;
3359 return true;
3360 }
3361
3362 bool WasNegative = Value.isNegative();
3363 if (AccessKind == AK_Increment) {
3364 ++Value;
3365
3366 if (!WasNegative && Value.isNegative() &&
3367 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3368 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003369 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003370 }
3371 } else {
3372 --Value;
3373
3374 if (WasNegative && !Value.isNegative() &&
3375 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3376 unsigned BitWidth = Value.getBitWidth();
3377 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3378 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003379 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003380 }
3381 }
3382 return true;
3383 }
3384 bool found(APFloat &Value, QualType SubobjType) {
3385 if (!checkConst(SubobjType))
3386 return false;
3387
3388 if (Old) *Old = APValue(Value);
3389
3390 APFloat One(Value.getSemantics(), 1);
3391 if (AccessKind == AK_Increment)
3392 Value.add(One, APFloat::rmNearestTiesToEven);
3393 else
3394 Value.subtract(One, APFloat::rmNearestTiesToEven);
3395 return true;
3396 }
3397 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3398 if (!checkConst(SubobjType))
3399 return false;
3400
3401 QualType PointeeType;
3402 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3403 PointeeType = PT->getPointeeType();
3404 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003405 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003406 return false;
3407 }
3408
3409 LValue LVal;
3410 LVal.setFrom(Info.Ctx, Subobj);
3411 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3412 AccessKind == AK_Increment ? 1 : -1))
3413 return false;
3414 LVal.moveInto(Subobj);
3415 return true;
3416 }
3417 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3418 llvm_unreachable("shouldn't encounter string elements here");
3419 }
3420};
3421} // end anonymous namespace
3422
3423/// Perform an increment or decrement on LVal.
3424static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3425 QualType LValType, bool IsIncrement, APValue *Old) {
3426 if (LVal.Designator.Invalid)
3427 return false;
3428
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003429 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003430 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003431 return false;
3432 }
3433
3434 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3435 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3436 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3437 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3438}
3439
Richard Smithe97cbd72011-11-11 04:05:33 +00003440/// Build an lvalue for the object argument of a member function call.
3441static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3442 LValue &This) {
3443 if (Object->getType()->isPointerType())
3444 return EvaluatePointer(Object, This, Info);
3445
3446 if (Object->isGLValue())
3447 return EvaluateLValue(Object, This, Info);
3448
Richard Smithd9f663b2013-04-22 15:31:51 +00003449 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003450 return EvaluateTemporary(Object, This, Info);
3451
Faisal Valie690b7a2016-07-02 22:34:24 +00003452 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003453 return false;
3454}
3455
3456/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3457/// lvalue referring to the result.
3458///
3459/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003460/// \param LV - An lvalue referring to the base of the member pointer.
3461/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003462/// \param IncludeMember - Specifies whether the member itself is included in
3463/// the resulting LValue subobject designator. This is not possible when
3464/// creating a bound member function.
3465/// \return The field or method declaration to which the member pointer refers,
3466/// or 0 if evaluation fails.
3467static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003468 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003469 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003470 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003471 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003472 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003473 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003474 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003475
3476 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3477 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003478 if (!MemPtr.getDecl()) {
3479 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003480 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003481 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003482 }
Richard Smith253c2a32012-01-27 01:14:48 +00003483
Richard Smith027bf112011-11-17 22:56:20 +00003484 if (MemPtr.isDerivedMember()) {
3485 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003486 // The end of the derived-to-base path for the base object must match the
3487 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003488 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003489 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003490 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003491 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003492 }
Richard Smith027bf112011-11-17 22:56:20 +00003493 unsigned PathLengthToMember =
3494 LV.Designator.Entries.size() - MemPtr.Path.size();
3495 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3496 const CXXRecordDecl *LVDecl = getAsBaseClass(
3497 LV.Designator.Entries[PathLengthToMember + I]);
3498 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003499 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003500 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003501 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003502 }
Richard Smith027bf112011-11-17 22:56:20 +00003503 }
3504
3505 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003506 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003507 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003508 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003509 } else if (!MemPtr.Path.empty()) {
3510 // Extend the LValue path with the member pointer's path.
3511 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3512 MemPtr.Path.size() + IncludeMember);
3513
3514 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003515 if (const PointerType *PT = LVType->getAs<PointerType>())
3516 LVType = PT->getPointeeType();
3517 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3518 assert(RD && "member pointer access on non-class-type expression");
3519 // The first class in the path is that of the lvalue.
3520 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3521 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003522 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003523 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003524 RD = Base;
3525 }
3526 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003527 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3528 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003529 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003530 }
3531
3532 // Add the member. Note that we cannot build bound member functions here.
3533 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003534 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003535 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003536 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003537 } else if (const IndirectFieldDecl *IFD =
3538 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003539 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003540 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003541 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003542 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003543 }
Richard Smith027bf112011-11-17 22:56:20 +00003544 }
3545
3546 return MemPtr.getDecl();
3547}
3548
Richard Smith84401042013-06-03 05:03:02 +00003549static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3550 const BinaryOperator *BO,
3551 LValue &LV,
3552 bool IncludeMember = true) {
3553 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3554
3555 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003556 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003557 MemberPtr MemPtr;
3558 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3559 }
Craig Topper36250ad2014-05-12 05:36:57 +00003560 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003561 }
3562
3563 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3564 BO->getRHS(), IncludeMember);
3565}
3566
Richard Smith027bf112011-11-17 22:56:20 +00003567/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3568/// the provided lvalue, which currently refers to the base object.
3569static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3570 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003571 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003572 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003573 return false;
3574
Richard Smitha8105bc2012-01-06 16:39:00 +00003575 QualType TargetQT = E->getType();
3576 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3577 TargetQT = PT->getPointeeType();
3578
3579 // Check this cast lands within the final derived-to-base subobject path.
3580 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003581 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003582 << D.MostDerivedType << TargetQT;
3583 return false;
3584 }
3585
Richard Smith027bf112011-11-17 22:56:20 +00003586 // Check the type of the final cast. We don't need to check the path,
3587 // since a cast can only be formed if the path is unique.
3588 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003589 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3590 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003591 if (NewEntriesSize == D.MostDerivedPathLength)
3592 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3593 else
Richard Smith027bf112011-11-17 22:56:20 +00003594 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003595 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003596 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003597 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003598 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003599 }
Richard Smith027bf112011-11-17 22:56:20 +00003600
3601 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003602 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003603}
3604
Mike Stump876387b2009-10-27 22:09:17 +00003605namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003606enum EvalStmtResult {
3607 /// Evaluation failed.
3608 ESR_Failed,
3609 /// Hit a 'return' statement.
3610 ESR_Returned,
3611 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003612 ESR_Succeeded,
3613 /// Hit a 'continue' statement.
3614 ESR_Continue,
3615 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003616 ESR_Break,
3617 /// Still scanning for 'case' or 'default' statement.
3618 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003619};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003620}
Richard Smith254a73d2011-10-28 22:34:42 +00003621
Richard Smith97fcf4b2016-08-14 23:15:52 +00003622static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3623 // We don't need to evaluate the initializer for a static local.
3624 if (!VD->hasLocalStorage())
3625 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003626
Richard Smith97fcf4b2016-08-14 23:15:52 +00003627 LValue Result;
3628 Result.set(VD, Info.CurrentCall->Index);
3629 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003630
Richard Smith97fcf4b2016-08-14 23:15:52 +00003631 const Expr *InitE = VD->getInit();
3632 if (!InitE) {
3633 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3634 << false << VD->getType();
3635 Val = APValue();
3636 return false;
3637 }
Richard Smith51f03172013-06-20 03:00:05 +00003638
Richard Smith97fcf4b2016-08-14 23:15:52 +00003639 if (InitE->isValueDependent())
3640 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003641
Richard Smith97fcf4b2016-08-14 23:15:52 +00003642 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3643 // Wipe out any partially-computed value, to allow tracking that this
3644 // evaluation failed.
3645 Val = APValue();
3646 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003647 }
3648
3649 return true;
3650}
3651
Richard Smith97fcf4b2016-08-14 23:15:52 +00003652static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3653 bool OK = true;
3654
3655 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3656 OK &= EvaluateVarDecl(Info, VD);
3657
3658 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3659 for (auto *BD : DD->bindings())
3660 if (auto *VD = BD->getHoldingVar())
3661 OK &= EvaluateDecl(Info, VD);
3662
3663 return OK;
3664}
3665
3666
Richard Smith4e18ca52013-05-06 05:56:11 +00003667/// Evaluate a condition (either a variable declaration or an expression).
3668static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3669 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003670 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003671 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3672 return false;
3673 return EvaluateAsBooleanCondition(Cond, Result, Info);
3674}
3675
Richard Smith89210072016-04-04 23:29:43 +00003676namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003677/// \brief A location where the result (returned value) of evaluating a
3678/// statement should be stored.
3679struct StmtResult {
3680 /// The APValue that should be filled in with the returned value.
3681 APValue &Value;
3682 /// The location containing the result, if any (used to support RVO).
3683 const LValue *Slot;
3684};
Richard Smith89210072016-04-04 23:29:43 +00003685}
Richard Smith52a980a2015-08-28 02:43:42 +00003686
3687static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003688 const Stmt *S,
3689 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003690
3691/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003692static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003693 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003694 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003695 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003696 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003697 case ESR_Break:
3698 return ESR_Succeeded;
3699 case ESR_Succeeded:
3700 case ESR_Continue:
3701 return ESR_Continue;
3702 case ESR_Failed:
3703 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003704 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003705 return ESR;
3706 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003707 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003708}
3709
Richard Smith496ddcf2013-05-12 17:32:42 +00003710/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003711static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003712 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003713 BlockScopeRAII Scope(Info);
3714
Richard Smith496ddcf2013-05-12 17:32:42 +00003715 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003716 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003717 {
3718 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003719 if (const Stmt *Init = SS->getInit()) {
3720 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3721 if (ESR != ESR_Succeeded)
3722 return ESR;
3723 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003724 if (SS->getConditionVariable() &&
3725 !EvaluateDecl(Info, SS->getConditionVariable()))
3726 return ESR_Failed;
3727 if (!EvaluateInteger(SS->getCond(), Value, Info))
3728 return ESR_Failed;
3729 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003730
3731 // Find the switch case corresponding to the value of the condition.
3732 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003733 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003734 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3735 SC = SC->getNextSwitchCase()) {
3736 if (isa<DefaultStmt>(SC)) {
3737 Found = SC;
3738 continue;
3739 }
3740
3741 const CaseStmt *CS = cast<CaseStmt>(SC);
3742 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3743 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3744 : LHS;
3745 if (LHS <= Value && Value <= RHS) {
3746 Found = SC;
3747 break;
3748 }
3749 }
3750
3751 if (!Found)
3752 return ESR_Succeeded;
3753
3754 // Search the switch body for the switch case and evaluate it from there.
3755 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3756 case ESR_Break:
3757 return ESR_Succeeded;
3758 case ESR_Succeeded:
3759 case ESR_Continue:
3760 case ESR_Failed:
3761 case ESR_Returned:
3762 return ESR;
3763 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003764 // This can only happen if the switch case is nested within a statement
3765 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003766 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003767 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003768 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003769 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003770}
3771
Richard Smith254a73d2011-10-28 22:34:42 +00003772// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003773static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003774 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003775 if (!Info.nextStep(S))
3776 return ESR_Failed;
3777
Richard Smith496ddcf2013-05-12 17:32:42 +00003778 // If we're hunting down a 'case' or 'default' label, recurse through
3779 // substatements until we hit the label.
3780 if (Case) {
3781 // FIXME: We don't start the lifetime of objects whose initialization we
3782 // jump over. However, such objects must be of class type with a trivial
3783 // default constructor that initialize all subobjects, so must be empty,
3784 // so this almost never matters.
3785 switch (S->getStmtClass()) {
3786 case Stmt::CompoundStmtClass:
3787 // FIXME: Precompute which substatement of a compound statement we
3788 // would jump to, and go straight there rather than performing a
3789 // linear scan each time.
3790 case Stmt::LabelStmtClass:
3791 case Stmt::AttributedStmtClass:
3792 case Stmt::DoStmtClass:
3793 break;
3794
3795 case Stmt::CaseStmtClass:
3796 case Stmt::DefaultStmtClass:
3797 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003798 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003799 break;
3800
3801 case Stmt::IfStmtClass: {
3802 // FIXME: Precompute which side of an 'if' we would jump to, and go
3803 // straight there rather than scanning both sides.
3804 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003805
3806 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3807 // preceded by our switch label.
3808 BlockScopeRAII Scope(Info);
3809
Richard Smith496ddcf2013-05-12 17:32:42 +00003810 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3811 if (ESR != ESR_CaseNotFound || !IS->getElse())
3812 return ESR;
3813 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3814 }
3815
3816 case Stmt::WhileStmtClass: {
3817 EvalStmtResult ESR =
3818 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3819 if (ESR != ESR_Continue)
3820 return ESR;
3821 break;
3822 }
3823
3824 case Stmt::ForStmtClass: {
3825 const ForStmt *FS = cast<ForStmt>(S);
3826 EvalStmtResult ESR =
3827 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3828 if (ESR != ESR_Continue)
3829 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003830 if (FS->getInc()) {
3831 FullExpressionRAII IncScope(Info);
3832 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3833 return ESR_Failed;
3834 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003835 break;
3836 }
3837
3838 case Stmt::DeclStmtClass:
3839 // FIXME: If the variable has initialization that can't be jumped over,
3840 // bail out of any immediately-surrounding compound-statement too.
3841 default:
3842 return ESR_CaseNotFound;
3843 }
3844 }
3845
Richard Smith254a73d2011-10-28 22:34:42 +00003846 switch (S->getStmtClass()) {
3847 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003848 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003849 // Don't bother evaluating beyond an expression-statement which couldn't
3850 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003851 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003852 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003853 return ESR_Failed;
3854 return ESR_Succeeded;
3855 }
3856
Faisal Valie690b7a2016-07-02 22:34:24 +00003857 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003858 return ESR_Failed;
3859
3860 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003861 return ESR_Succeeded;
3862
Richard Smithd9f663b2013-04-22 15:31:51 +00003863 case Stmt::DeclStmtClass: {
3864 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003865 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003866 // Each declaration initialization is its own full-expression.
3867 // FIXME: This isn't quite right; if we're performing aggregate
3868 // initialization, each braced subexpression is its own full-expression.
3869 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003870 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003871 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003872 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003873 return ESR_Succeeded;
3874 }
3875
Richard Smith357362d2011-12-13 06:39:58 +00003876 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003877 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003878 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003879 if (RetExpr &&
3880 !(Result.Slot
3881 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3882 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003883 return ESR_Failed;
3884 return ESR_Returned;
3885 }
Richard Smith254a73d2011-10-28 22:34:42 +00003886
3887 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003888 BlockScopeRAII Scope(Info);
3889
Richard Smith254a73d2011-10-28 22:34:42 +00003890 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003891 for (const auto *BI : CS->body()) {
3892 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003893 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003894 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003895 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003896 return ESR;
3897 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003898 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003899 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003900
3901 case Stmt::IfStmtClass: {
3902 const IfStmt *IS = cast<IfStmt>(S);
3903
3904 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003905 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003906 if (const Stmt *Init = IS->getInit()) {
3907 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3908 if (ESR != ESR_Succeeded)
3909 return ESR;
3910 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003911 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003912 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003913 return ESR_Failed;
3914
3915 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3916 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3917 if (ESR != ESR_Succeeded)
3918 return ESR;
3919 }
3920 return ESR_Succeeded;
3921 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003922
3923 case Stmt::WhileStmtClass: {
3924 const WhileStmt *WS = cast<WhileStmt>(S);
3925 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003926 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003927 bool Continue;
3928 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3929 Continue))
3930 return ESR_Failed;
3931 if (!Continue)
3932 break;
3933
3934 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3935 if (ESR != ESR_Continue)
3936 return ESR;
3937 }
3938 return ESR_Succeeded;
3939 }
3940
3941 case Stmt::DoStmtClass: {
3942 const DoStmt *DS = cast<DoStmt>(S);
3943 bool Continue;
3944 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003945 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003946 if (ESR != ESR_Continue)
3947 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003948 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003949
Richard Smith08d6a2c2013-07-24 07:11:57 +00003950 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003951 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3952 return ESR_Failed;
3953 } while (Continue);
3954 return ESR_Succeeded;
3955 }
3956
3957 case Stmt::ForStmtClass: {
3958 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003959 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003960 if (FS->getInit()) {
3961 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3962 if (ESR != ESR_Succeeded)
3963 return ESR;
3964 }
3965 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003966 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003967 bool Continue = true;
3968 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3969 FS->getCond(), Continue))
3970 return ESR_Failed;
3971 if (!Continue)
3972 break;
3973
3974 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3975 if (ESR != ESR_Continue)
3976 return ESR;
3977
Richard Smith08d6a2c2013-07-24 07:11:57 +00003978 if (FS->getInc()) {
3979 FullExpressionRAII IncScope(Info);
3980 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3981 return ESR_Failed;
3982 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003983 }
3984 return ESR_Succeeded;
3985 }
3986
Richard Smith896e0d72013-05-06 06:51:17 +00003987 case Stmt::CXXForRangeStmtClass: {
3988 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003989 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003990
3991 // Initialize the __range variable.
3992 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3993 if (ESR != ESR_Succeeded)
3994 return ESR;
3995
3996 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003997 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3998 if (ESR != ESR_Succeeded)
3999 return ESR;
4000 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004001 if (ESR != ESR_Succeeded)
4002 return ESR;
4003
4004 while (true) {
4005 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004006 {
4007 bool Continue = true;
4008 FullExpressionRAII CondExpr(Info);
4009 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4010 return ESR_Failed;
4011 if (!Continue)
4012 break;
4013 }
Richard Smith896e0d72013-05-06 06:51:17 +00004014
4015 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004016 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004017 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4018 if (ESR != ESR_Succeeded)
4019 return ESR;
4020
4021 // Loop body.
4022 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4023 if (ESR != ESR_Continue)
4024 return ESR;
4025
4026 // Increment: ++__begin
4027 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4028 return ESR_Failed;
4029 }
4030
4031 return ESR_Succeeded;
4032 }
4033
Richard Smith496ddcf2013-05-12 17:32:42 +00004034 case Stmt::SwitchStmtClass:
4035 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4036
Richard Smith4e18ca52013-05-06 05:56:11 +00004037 case Stmt::ContinueStmtClass:
4038 return ESR_Continue;
4039
4040 case Stmt::BreakStmtClass:
4041 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004042
4043 case Stmt::LabelStmtClass:
4044 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4045
4046 case Stmt::AttributedStmtClass:
4047 // As a general principle, C++11 attributes can be ignored without
4048 // any semantic impact.
4049 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4050 Case);
4051
4052 case Stmt::CaseStmtClass:
4053 case Stmt::DefaultStmtClass:
4054 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004055 }
4056}
4057
Richard Smithcc36f692011-12-22 02:22:31 +00004058/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4059/// default constructor. If so, we'll fold it whether or not it's marked as
4060/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4061/// so we need special handling.
4062static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004063 const CXXConstructorDecl *CD,
4064 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004065 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4066 return false;
4067
Richard Smith66e05fe2012-01-18 05:21:49 +00004068 // Value-initialization does not call a trivial default constructor, so such a
4069 // call is a core constant expression whether or not the constructor is
4070 // constexpr.
4071 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004072 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004073 // FIXME: If DiagDecl is an implicitly-declared special member function,
4074 // we should be much more explicit about why it's not constexpr.
4075 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4076 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4077 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004078 } else {
4079 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4080 }
4081 }
4082 return true;
4083}
4084
Richard Smith357362d2011-12-13 06:39:58 +00004085/// CheckConstexprFunction - Check that a function can be called in a constant
4086/// expression.
4087static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4088 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004089 const FunctionDecl *Definition,
4090 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004091 // Potential constant expressions can contain calls to declared, but not yet
4092 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004093 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004094 Declaration->isConstexpr())
4095 return false;
4096
Richard Smith0838f3a2013-05-14 05:18:44 +00004097 // Bail out with no diagnostic if the function declaration itself is invalid.
4098 // We will have produced a relevant diagnostic while parsing it.
4099 if (Declaration->isInvalidDecl())
4100 return false;
4101
Richard Smith357362d2011-12-13 06:39:58 +00004102 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004103 if (Definition && Definition->isConstexpr() &&
4104 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004105 return true;
4106
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004107 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004108 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Daniel Jasperffdee092017-05-02 19:21:42 +00004109
Richard Smith5179eb72016-06-28 19:03:57 +00004110 // If this function is not constexpr because it is an inherited
4111 // non-constexpr constructor, diagnose that directly.
4112 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4113 if (CD && CD->isInheritingConstructor()) {
4114 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Daniel Jasperffdee092017-05-02 19:21:42 +00004115 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004116 DiagDecl = CD = Inherited;
4117 }
4118
4119 // FIXME: If DiagDecl is an implicitly-declared special member function
4120 // or an inheriting constructor, we should be much more explicit about why
4121 // it's not constexpr.
4122 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004123 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004124 << CD->getInheritedConstructor().getConstructor()->getParent();
4125 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004126 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004127 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004128 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4129 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004130 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004131 }
4132 return false;
4133}
4134
Richard Smithbe6dd812014-11-19 21:27:17 +00004135/// Determine if a class has any fields that might need to be copied by a
4136/// trivial copy or move operation.
4137static bool hasFields(const CXXRecordDecl *RD) {
4138 if (!RD || RD->isEmpty())
4139 return false;
4140 for (auto *FD : RD->fields()) {
4141 if (FD->isUnnamedBitfield())
4142 continue;
4143 return true;
4144 }
4145 for (auto &Base : RD->bases())
4146 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4147 return true;
4148 return false;
4149}
4150
Richard Smithd62306a2011-11-10 06:34:14 +00004151namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004152typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004153}
4154
4155/// EvaluateArgs - Evaluate the arguments to a function call.
4156static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4157 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004158 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004159 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004160 I != E; ++I) {
4161 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4162 // If we're checking for a potential constant expression, evaluate all
4163 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004164 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004165 return false;
4166 Success = false;
4167 }
4168 }
4169 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004170}
4171
Richard Smith254a73d2011-10-28 22:34:42 +00004172/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004173static bool HandleFunctionCall(SourceLocation CallLoc,
4174 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004175 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004176 EvalInfo &Info, APValue &Result,
4177 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004178 ArgVector ArgValues(Args.size());
4179 if (!EvaluateArgs(Args, ArgValues, Info))
4180 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004181
Richard Smith253c2a32012-01-27 01:14:48 +00004182 if (!Info.CheckCallLimit(CallLoc))
4183 return false;
4184
4185 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004186
4187 // For a trivial copy or move assignment, perform an APValue copy. This is
4188 // essential for unions, where the operations performed by the assignment
4189 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004190 //
4191 // Skip this for non-union classes with no fields; in that case, the defaulted
4192 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004193 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004194 if (MD && MD->isDefaulted() &&
4195 (MD->getParent()->isUnion() ||
4196 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004197 assert(This &&
4198 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4199 LValue RHS;
4200 RHS.setFrom(Info.Ctx, ArgValues[0]);
4201 APValue RHSValue;
4202 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4203 RHS, RHSValue))
4204 return false;
4205 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4206 RHSValue))
4207 return false;
4208 This->moveInto(Result);
4209 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004210 } else if (MD && isLambdaCallOperator(MD)) {
4211 // We're in a lambda; determine the lambda capture field maps.
4212 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4213 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004214 }
4215
Richard Smith52a980a2015-08-28 02:43:42 +00004216 StmtResult Ret = {Result, ResultSlot};
4217 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004218 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004219 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004220 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004221 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004222 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004223 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004224}
4225
Richard Smithd62306a2011-11-10 06:34:14 +00004226/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004227static bool HandleConstructorCall(const Expr *E, const LValue &This,
4228 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004229 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004230 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004231 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004232 if (!Info.CheckCallLimit(CallLoc))
4233 return false;
4234
Richard Smith3607ffe2012-02-13 03:54:03 +00004235 const CXXRecordDecl *RD = Definition->getParent();
4236 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004237 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004238 return false;
4239 }
4240
Richard Smith5179eb72016-06-28 19:03:57 +00004241 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004242
Richard Smith52a980a2015-08-28 02:43:42 +00004243 // FIXME: Creating an APValue just to hold a nonexistent return value is
4244 // wasteful.
4245 APValue RetVal;
4246 StmtResult Ret = {RetVal, nullptr};
4247
Richard Smith5179eb72016-06-28 19:03:57 +00004248 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004249 if (Definition->isDelegatingConstructor()) {
4250 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004251 {
4252 FullExpressionRAII InitScope(Info);
4253 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4254 return false;
4255 }
Richard Smith52a980a2015-08-28 02:43:42 +00004256 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004257 }
4258
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004259 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004260 // essential for unions (or classes with anonymous union members), where the
4261 // operations performed by the constructor cannot be represented by
4262 // ctor-initializers.
4263 //
4264 // Skip this for empty non-union classes; we should not perform an
4265 // lvalue-to-rvalue conversion on them because their copy constructor does not
4266 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004267 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004268 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004269 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004270 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004271 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004272 return handleLValueToRValueConversion(
4273 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4274 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004275 }
4276
4277 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004278 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004279 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004280 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004281
John McCalld7bca762012-05-01 00:38:49 +00004282 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004283 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4284
Richard Smith08d6a2c2013-07-24 07:11:57 +00004285 // A scope for temporaries lifetime-extended by reference members.
4286 BlockScopeRAII LifetimeExtendedScope(Info);
4287
Richard Smith253c2a32012-01-27 01:14:48 +00004288 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004289 unsigned BasesSeen = 0;
4290#ifndef NDEBUG
4291 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4292#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004293 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004294 LValue Subobject = This;
4295 APValue *Value = &Result;
4296
4297 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004298 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004299 if (I->isBaseInitializer()) {
4300 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004301#ifndef NDEBUG
4302 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004303 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004304 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4305 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4306 "base class initializers not in expected order");
4307 ++BaseIt;
4308#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004309 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004310 BaseType->getAsCXXRecordDecl(), &Layout))
4311 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004312 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004313 } else if ((FD = I->getMember())) {
4314 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004315 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004316 if (RD->isUnion()) {
4317 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004318 Value = &Result.getUnionValue();
4319 } else {
4320 Value = &Result.getStructField(FD->getFieldIndex());
4321 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004322 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004323 // Walk the indirect field decl's chain to find the object to initialize,
4324 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004325 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004326 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004327 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4328 // Switch the union field if it differs. This happens if we had
4329 // preceding zero-initialization, and we're now initializing a union
4330 // subobject other than the first.
4331 // FIXME: In this case, the values of the other subobjects are
4332 // specified, since zero-initialization sets all padding bits to zero.
4333 if (Value->isUninit() ||
4334 (Value->isUnion() && Value->getUnionField() != FD)) {
4335 if (CD->isUnion())
4336 *Value = APValue(FD);
4337 else
4338 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004339 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004340 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004341 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004342 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004343 if (CD->isUnion())
4344 Value = &Value->getUnionValue();
4345 else
4346 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004347 }
Richard Smithd62306a2011-11-10 06:34:14 +00004348 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004349 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004350 }
Richard Smith253c2a32012-01-27 01:14:48 +00004351
Richard Smith08d6a2c2013-07-24 07:11:57 +00004352 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004353 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4354 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004355 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004356 // If we're checking for a potential constant expression, evaluate all
4357 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004358 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004359 return false;
4360 Success = false;
4361 }
Richard Smithd62306a2011-11-10 06:34:14 +00004362 }
4363
Richard Smithd9f663b2013-04-22 15:31:51 +00004364 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004365 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004366}
4367
Richard Smith5179eb72016-06-28 19:03:57 +00004368static bool HandleConstructorCall(const Expr *E, const LValue &This,
4369 ArrayRef<const Expr*> Args,
4370 const CXXConstructorDecl *Definition,
4371 EvalInfo &Info, APValue &Result) {
4372 ArgVector ArgValues(Args.size());
4373 if (!EvaluateArgs(Args, ArgValues, Info))
4374 return false;
4375
4376 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4377 Info, Result);
4378}
4379
Eli Friedman9a156e52008-11-12 09:44:48 +00004380//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004381// Generic Evaluation
4382//===----------------------------------------------------------------------===//
4383namespace {
4384
Aaron Ballman68af21c2014-01-03 19:26:43 +00004385template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004386class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004387 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004388private:
Richard Smith52a980a2015-08-28 02:43:42 +00004389 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004390 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004391 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004392 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004393 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004394 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004395 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004396
Richard Smith17100ba2012-02-16 02:46:34 +00004397 // Check whether a conditional operator with a non-constant condition is a
4398 // potential constant expression. If neither arm is a potential constant
4399 // expression, then the conditional operator is not either.
4400 template<typename ConditionalOperator>
4401 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004402 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004403
4404 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004405 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004406 {
Richard Smith17100ba2012-02-16 02:46:34 +00004407 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004408 StmtVisitorTy::Visit(E->getFalseExpr());
4409 if (Diag.empty())
4410 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004411 }
Richard Smith17100ba2012-02-16 02:46:34 +00004412
George Burgess IV8c892b52016-05-25 22:31:54 +00004413 {
4414 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004415 Diag.clear();
4416 StmtVisitorTy::Visit(E->getTrueExpr());
4417 if (Diag.empty())
4418 return;
4419 }
4420
4421 Error(E, diag::note_constexpr_conditional_never_const);
4422 }
4423
4424
4425 template<typename ConditionalOperator>
4426 bool HandleConditionalOperator(const ConditionalOperator *E) {
4427 bool BoolResult;
4428 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004429 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004430 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004431 return false;
4432 }
4433 if (Info.noteFailure()) {
4434 StmtVisitorTy::Visit(E->getTrueExpr());
4435 StmtVisitorTy::Visit(E->getFalseExpr());
4436 }
Richard Smith17100ba2012-02-16 02:46:34 +00004437 return false;
4438 }
4439
4440 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4441 return StmtVisitorTy::Visit(EvalExpr);
4442 }
4443
Peter Collingbournee9200682011-05-13 03:29:01 +00004444protected:
4445 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004446 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004447 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4448
Richard Smith92b1ce02011-12-12 09:28:41 +00004449 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004450 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004451 }
4452
Aaron Ballman68af21c2014-01-03 19:26:43 +00004453 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004454
4455public:
4456 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4457
4458 EvalInfo &getEvalInfo() { return Info; }
4459
Richard Smithf57d8cb2011-12-09 22:58:01 +00004460 /// Report an evaluation error. This should only be called when an error is
4461 /// first discovered. When propagating an error, just return false.
4462 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004463 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004464 return false;
4465 }
4466 bool Error(const Expr *E) {
4467 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4468 }
4469
Aaron Ballman68af21c2014-01-03 19:26:43 +00004470 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004471 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004472 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004473 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004474 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004475 }
4476
Aaron Ballman68af21c2014-01-03 19:26:43 +00004477 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004478 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004479 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004480 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004481 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004482 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004483 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004484 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004485 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004486 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004487 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004488 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004489 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004490 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004491 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004492 // The initializer may not have been parsed yet, or might be erroneous.
4493 if (!E->getExpr())
4494 return Error(E);
4495 return StmtVisitorTy::Visit(E->getExpr());
4496 }
Richard Smith5894a912011-12-19 22:12:41 +00004497 // We cannot create any objects for which cleanups are required, so there is
4498 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004499 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004500 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004501
Aaron Ballman68af21c2014-01-03 19:26:43 +00004502 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004503 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4504 return static_cast<Derived*>(this)->VisitCastExpr(E);
4505 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004506 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004507 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4508 return static_cast<Derived*>(this)->VisitCastExpr(E);
4509 }
4510
Aaron Ballman68af21c2014-01-03 19:26:43 +00004511 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004512 switch (E->getOpcode()) {
4513 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004514 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004515
4516 case BO_Comma:
4517 VisitIgnoredValue(E->getLHS());
4518 return StmtVisitorTy::Visit(E->getRHS());
4519
4520 case BO_PtrMemD:
4521 case BO_PtrMemI: {
4522 LValue Obj;
4523 if (!HandleMemberPointerAccess(Info, E, Obj))
4524 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004525 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004526 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004527 return false;
4528 return DerivedSuccess(Result, E);
4529 }
4530 }
4531 }
4532
Aaron Ballman68af21c2014-01-03 19:26:43 +00004533 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004534 // Evaluate and cache the common expression. We treat it as a temporary,
4535 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004536 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004537 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004538 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004539
Richard Smith17100ba2012-02-16 02:46:34 +00004540 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004541 }
4542
Aaron Ballman68af21c2014-01-03 19:26:43 +00004543 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004544 bool IsBcpCall = false;
4545 // If the condition (ignoring parens) is a __builtin_constant_p call,
4546 // the result is a constant expression if it can be folded without
4547 // side-effects. This is an important GNU extension. See GCC PR38377
4548 // for discussion.
4549 if (const CallExpr *CallCE =
4550 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004551 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004552 IsBcpCall = true;
4553
4554 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4555 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004556 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004557 return false;
4558
Richard Smith6d4c6582013-11-05 22:18:15 +00004559 FoldConstant Fold(Info, IsBcpCall);
4560 if (!HandleConditionalOperator(E)) {
4561 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004562 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004563 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004564
4565 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004566 }
4567
Aaron Ballman68af21c2014-01-03 19:26:43 +00004568 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004569 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4570 return DerivedSuccess(*Value, E);
4571
4572 const Expr *Source = E->getSourceExpr();
4573 if (!Source)
4574 return Error(E);
4575 if (Source == E) { // sanity checking.
4576 assert(0 && "OpaqueValueExpr recursively refers to itself");
4577 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004578 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004579 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004580 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004581
Aaron Ballman68af21c2014-01-03 19:26:43 +00004582 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004583 APValue Result;
4584 if (!handleCallExpr(E, Result, nullptr))
4585 return false;
4586 return DerivedSuccess(Result, E);
4587 }
4588
4589 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky9add1592017-05-17 23:56:54 +00004590 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004591 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004592 QualType CalleeType = Callee->getType();
4593
Craig Topper36250ad2014-05-12 05:36:57 +00004594 const FunctionDecl *FD = nullptr;
4595 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004596 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004597 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004598
Nick Lewycky9add1592017-05-17 23:56:54 +00004599 struct EvaluateIgnoredRAII {
4600 public:
4601 EvaluateIgnoredRAII(EvalInfo &Info, llvm::ArrayRef<const Expr*> ToEval)
4602 : Info(Info), ToEval(ToEval) {}
4603 ~EvaluateIgnoredRAII() {
4604 if (Info.noteFailure()) {
4605 for (auto E : ToEval)
4606 EvaluateIgnoredValue(Info, E);
4607 }
4608 }
4609 void cancel() { ToEval = {}; }
4610 void drop_front() { ToEval = ToEval.drop_front(); }
4611 private:
4612 EvalInfo &Info;
4613 llvm::ArrayRef<const Expr*> ToEval;
4614 } EvalArguments(Info, Args);
4615
Richard Smithe97cbd72011-11-11 04:05:33 +00004616 // Extract function decl and 'this' pointer from the callee.
4617 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004618 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004619 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4620 // Explicit bound member calls, such as x.f() or p->g();
4621 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004622 return false;
4623 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004624 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004625 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004626 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4627 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004628 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4629 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004630 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004631 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004632 return Error(Callee);
4633
4634 FD = dyn_cast<FunctionDecl>(Member);
4635 if (!FD)
4636 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004637 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004638 LValue Call;
4639 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004640 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004641
Richard Smitha8105bc2012-01-06 16:39:00 +00004642 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004643 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004644 FD = dyn_cast_or_null<FunctionDecl>(
4645 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004646 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004647 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004648 // Don't call function pointers which have been cast to some other type.
4649 // Per DR (no number yet), the caller and callee can differ in noexcept.
4650 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4651 CalleeType->getPointeeType(), FD->getType())) {
4652 return Error(E);
4653 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004654
4655 // Overloaded operator calls to member functions are represented as normal
4656 // calls with '*this' as the first argument.
4657 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4658 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004659 // FIXME: When selecting an implicit conversion for an overloaded
4660 // operator delete, we sometimes try to evaluate calls to conversion
4661 // operators without a 'this' parameter!
4662 if (Args.empty())
4663 return Error(E);
4664
Nick Lewycky9add1592017-05-17 23:56:54 +00004665 const Expr *FirstArg = Args[0];
4666 Args = Args.drop_front();
4667 EvalArguments.drop_front();
4668 if (!EvaluateObjectArgument(Info, FirstArg, ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004669 return false;
4670 This = &ThisVal;
Daniel Jasperffdee092017-05-02 19:21:42 +00004671 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004672 // Map the static invoker for the lambda back to the call operator.
4673 // Conveniently, we don't have to slice out the 'this' argument (as is
4674 // being done for the non-static case), since a static member function
4675 // doesn't have an implicit argument passed in.
4676 const CXXRecordDecl *ClosureClass = MD->getParent();
4677 assert(
4678 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4679 "Number of captures must be zero for conversion to function-ptr");
4680
4681 const CXXMethodDecl *LambdaCallOp =
4682 ClosureClass->getLambdaCallOperator();
4683
4684 // Set 'FD', the function that will be called below, to the call
4685 // operator. If the closure object represents a generic lambda, find
4686 // the corresponding specialization of the call operator.
4687
4688 if (ClosureClass->isGenericLambda()) {
4689 assert(MD->isFunctionTemplateSpecialization() &&
4690 "A generic lambda's static-invoker function must be a "
4691 "template specialization");
4692 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4693 FunctionTemplateDecl *CallOpTemplate =
4694 LambdaCallOp->getDescribedFunctionTemplate();
4695 void *InsertPos = nullptr;
4696 FunctionDecl *CorrespondingCallOpSpecialization =
4697 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4698 assert(CorrespondingCallOpSpecialization &&
4699 "We must always have a function call operator specialization "
4700 "that corresponds to our static invoker specialization");
4701 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4702 } else
4703 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004704 }
4705
Daniel Jasperffdee092017-05-02 19:21:42 +00004706
Richard Smithe97cbd72011-11-11 04:05:33 +00004707 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004708 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004709
Richard Smith47b34932012-02-01 02:39:43 +00004710 if (This && !This->checkSubobject(Info, E, CSK_This))
4711 return false;
4712
Richard Smith3607ffe2012-02-13 03:54:03 +00004713 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4714 // calls to such functions in constant expressions.
4715 if (This && !HasQualifier &&
4716 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4717 return Error(E, diag::note_constexpr_virtual_call);
4718
Craig Topper36250ad2014-05-12 05:36:57 +00004719 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004720 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004721
Nick Lewycky9add1592017-05-17 23:56:54 +00004722 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
4723 return false;
4724
4725 EvalArguments.cancel();
4726
4727 if (!HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004728 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004729 return false;
4730
Richard Smith52a980a2015-08-28 02:43:42 +00004731 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004732 }
4733
Aaron Ballman68af21c2014-01-03 19:26:43 +00004734 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004735 return StmtVisitorTy::Visit(E->getInitializer());
4736 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004737 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004738 if (E->getNumInits() == 0)
4739 return DerivedZeroInitialization(E);
4740 if (E->getNumInits() == 1)
4741 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004742 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004743 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004744 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004745 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004746 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004747 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004748 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004749 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004750 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004751 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004752 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004753
Richard Smithd62306a2011-11-10 06:34:14 +00004754 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004755 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004756 assert(!E->isArrow() && "missing call to bound member function?");
4757
Richard Smith2e312c82012-03-03 22:46:17 +00004758 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004759 if (!Evaluate(Val, Info, E->getBase()))
4760 return false;
4761
4762 QualType BaseTy = E->getBase()->getType();
4763
4764 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004765 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004766 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004767 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004768 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4769
Richard Smith3229b742013-05-05 21:17:10 +00004770 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004771 SubobjectDesignator Designator(BaseTy);
4772 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004773
Richard Smith3229b742013-05-05 21:17:10 +00004774 APValue Result;
4775 return extractSubobject(Info, E, Obj, Designator, Result) &&
4776 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004777 }
4778
Aaron Ballman68af21c2014-01-03 19:26:43 +00004779 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004780 switch (E->getCastKind()) {
4781 default:
4782 break;
4783
Richard Smitha23ab512013-05-23 00:30:41 +00004784 case CK_AtomicToNonAtomic: {
4785 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004786 // This does not need to be done in place even for class/array types:
4787 // atomic-to-non-atomic conversion implies copying the object
4788 // representation.
4789 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004790 return false;
4791 return DerivedSuccess(AtomicVal, E);
4792 }
4793
Richard Smith11562c52011-10-28 17:51:58 +00004794 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004795 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004796 return StmtVisitorTy::Visit(E->getSubExpr());
4797
4798 case CK_LValueToRValue: {
4799 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004800 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4801 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004802 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004803 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004804 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004805 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004806 return false;
4807 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004808 }
4809 }
4810
Richard Smithf57d8cb2011-12-09 22:58:01 +00004811 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004812 }
4813
Aaron Ballman68af21c2014-01-03 19:26:43 +00004814 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004815 return VisitUnaryPostIncDec(UO);
4816 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004817 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004818 return VisitUnaryPostIncDec(UO);
4819 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004820 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004821 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004822 return Error(UO);
4823
4824 LValue LVal;
4825 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4826 return false;
4827 APValue RVal;
4828 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4829 UO->isIncrementOp(), &RVal))
4830 return false;
4831 return DerivedSuccess(RVal, UO);
4832 }
4833
Aaron Ballman68af21c2014-01-03 19:26:43 +00004834 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004835 // We will have checked the full-expressions inside the statement expression
4836 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004837 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004838 return Error(E);
4839
Richard Smith08d6a2c2013-07-24 07:11:57 +00004840 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004841 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004842 if (CS->body_empty())
4843 return true;
4844
Richard Smith51f03172013-06-20 03:00:05 +00004845 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4846 BE = CS->body_end();
4847 /**/; ++BI) {
4848 if (BI + 1 == BE) {
4849 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4850 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004851 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004852 diag::note_constexpr_stmt_expr_unsupported);
4853 return false;
4854 }
4855 return this->Visit(FinalExpr);
4856 }
4857
4858 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004859 StmtResult Result = { ReturnValue, nullptr };
4860 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004861 if (ESR != ESR_Succeeded) {
4862 // FIXME: If the statement-expression terminated due to 'return',
4863 // 'break', or 'continue', it would be nice to propagate that to
4864 // the outer statement evaluation rather than bailing out.
4865 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004866 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004867 diag::note_constexpr_stmt_expr_unsupported);
4868 return false;
4869 }
4870 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004871
4872 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004873 }
4874
Richard Smith4a678122011-10-24 18:44:57 +00004875 /// Visit a value which is evaluated, but whose value is ignored.
4876 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004877 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004878 }
David Majnemere9807b22016-02-26 04:23:19 +00004879
4880 /// Potentially visit a MemberExpr's base expression.
4881 void VisitIgnoredBaseExpression(const Expr *E) {
4882 // While MSVC doesn't evaluate the base expression, it does diagnose the
4883 // presence of side-effecting behavior.
4884 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4885 return;
4886 VisitIgnoredValue(E);
4887 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004888};
4889
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004890}
Peter Collingbournee9200682011-05-13 03:29:01 +00004891
4892//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004893// Common base class for lvalue and temporary evaluation.
4894//===----------------------------------------------------------------------===//
4895namespace {
4896template<class Derived>
4897class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004898 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004899protected:
4900 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00004901 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00004902 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004903 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004904
4905 bool Success(APValue::LValueBase B) {
4906 Result.set(B);
4907 return true;
4908 }
4909
George Burgess IVf9013bf2017-02-10 22:52:29 +00004910 bool evaluatePointer(const Expr *E, LValue &Result) {
4911 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4912 }
4913
Richard Smith027bf112011-11-17 22:56:20 +00004914public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004915 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4916 : ExprEvaluatorBaseTy(Info), Result(Result),
4917 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00004918
Richard Smith2e312c82012-03-03 22:46:17 +00004919 bool Success(const APValue &V, const Expr *E) {
4920 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004921 return true;
4922 }
Richard Smith027bf112011-11-17 22:56:20 +00004923
Richard Smith027bf112011-11-17 22:56:20 +00004924 bool VisitMemberExpr(const MemberExpr *E) {
4925 // Handle non-static data members.
4926 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004927 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004928 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004929 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00004930 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004931 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004932 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004933 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004934 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004935 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004936 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004937 BaseTy = E->getBase()->getType();
4938 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004939 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004940 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004941 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004942 Result.setInvalid(E);
4943 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004944 }
Richard Smith027bf112011-11-17 22:56:20 +00004945
Richard Smith1b78b3d2012-01-25 22:15:11 +00004946 const ValueDecl *MD = E->getMemberDecl();
4947 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4948 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4949 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4950 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004951 if (!HandleLValueMember(this->Info, E, Result, FD))
4952 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004953 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004954 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4955 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004956 } else
4957 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004958
Richard Smith1b78b3d2012-01-25 22:15:11 +00004959 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004960 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004961 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004962 RefValue))
4963 return false;
4964 return Success(RefValue, E);
4965 }
4966 return true;
4967 }
4968
4969 bool VisitBinaryOperator(const BinaryOperator *E) {
4970 switch (E->getOpcode()) {
4971 default:
4972 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4973
4974 case BO_PtrMemD:
4975 case BO_PtrMemI:
4976 return HandleMemberPointerAccess(this->Info, E, Result);
4977 }
4978 }
4979
4980 bool VisitCastExpr(const CastExpr *E) {
4981 switch (E->getCastKind()) {
4982 default:
4983 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4984
4985 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004986 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004987 if (!this->Visit(E->getSubExpr()))
4988 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004989
4990 // Now figure out the necessary offset to add to the base LV to get from
4991 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004992 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4993 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004994 }
4995 }
4996};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004997}
Richard Smith027bf112011-11-17 22:56:20 +00004998
4999//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005000// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005001//
5002// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5003// function designators (in C), decl references to void objects (in C), and
5004// temporaries (if building with -Wno-address-of-temporary).
5005//
5006// LValue evaluation produces values comprising a base expression of one of the
5007// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005008// - Declarations
5009// * VarDecl
5010// * FunctionDecl
5011// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005012// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005013// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005014// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005015// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005016// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005017// * ObjCEncodeExpr
5018// * AddrLabelExpr
5019// * BlockExpr
5020// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005021// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005022// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005023// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005024// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5025// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005026// * A MaterializeTemporaryExpr that has static storage duration, with no
5027// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005028// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005029//===----------------------------------------------------------------------===//
5030namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005031class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005032 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005033public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005034 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5035 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005036
Richard Smith11562c52011-10-28 17:51:58 +00005037 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005038 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005039
Peter Collingbournee9200682011-05-13 03:29:01 +00005040 bool VisitDeclRefExpr(const DeclRefExpr *E);
5041 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005042 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005043 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5044 bool VisitMemberExpr(const MemberExpr *E);
5045 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5046 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005047 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005048 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005049 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5050 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005051 bool VisitUnaryReal(const UnaryOperator *E);
5052 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005053 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5054 return VisitUnaryPreIncDec(UO);
5055 }
5056 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5057 return VisitUnaryPreIncDec(UO);
5058 }
Richard Smith3229b742013-05-05 21:17:10 +00005059 bool VisitBinAssign(const BinaryOperator *BO);
5060 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005061
Peter Collingbournee9200682011-05-13 03:29:01 +00005062 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005063 switch (E->getCastKind()) {
5064 default:
Richard Smith027bf112011-11-17 22:56:20 +00005065 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005066
Eli Friedmance3e02a2011-10-11 00:13:24 +00005067 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005068 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005069 if (!Visit(E->getSubExpr()))
5070 return false;
5071 Result.Designator.setInvalid();
5072 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005073
Richard Smith027bf112011-11-17 22:56:20 +00005074 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005075 if (!Visit(E->getSubExpr()))
5076 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005077 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005078 }
5079 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005080};
5081} // end anonymous namespace
5082
Richard Smith11562c52011-10-28 17:51:58 +00005083/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005084/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005085/// * function designators in C, and
5086/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005087/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005088static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5089 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005090 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005091 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005092 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005093}
5094
Peter Collingbournee9200682011-05-13 03:29:01 +00005095bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005096 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005097 return Success(FD);
5098 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005099 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005100 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005101 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005102 return Error(E);
5103}
Richard Smith733237d2011-10-24 23:14:33 +00005104
Faisal Vali0528a312016-11-13 06:09:16 +00005105
Richard Smith11562c52011-10-28 17:51:58 +00005106bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005107
5108 // If we are within a lambda's call operator, check whether the 'VD' referred
5109 // to within 'E' actually represents a lambda-capture that maps to a
5110 // data-member/field within the closure object, and if so, evaluate to the
5111 // field or what the field refers to.
5112 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5113 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5114 if (Info.checkingPotentialConstantExpression())
5115 return false;
5116 // Start with 'Result' referring to the complete closure object...
5117 Result = *Info.CurrentCall->This;
5118 // ... then update it to refer to the field of the closure object
5119 // that represents the capture.
5120 if (!HandleLValueMember(Info, E, Result, FD))
5121 return false;
5122 // And if the field is of reference type, update 'Result' to refer to what
5123 // the field refers to.
5124 if (FD->getType()->isReferenceType()) {
5125 APValue RVal;
5126 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5127 RVal))
5128 return false;
5129 Result.setFrom(Info.Ctx, RVal);
5130 }
5131 return true;
5132 }
5133 }
Craig Topper36250ad2014-05-12 05:36:57 +00005134 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005135 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5136 // Only if a local variable was declared in the function currently being
5137 // evaluated, do we expect to be able to find its value in the current
5138 // frame. (Otherwise it was likely declared in an enclosing context and
5139 // could either have a valid evaluatable value (for e.g. a constexpr
5140 // variable) or be ill-formed (and trigger an appropriate evaluation
5141 // diagnostic)).
5142 if (Info.CurrentCall->Callee &&
5143 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5144 Frame = Info.CurrentCall;
5145 }
5146 }
Richard Smith3229b742013-05-05 21:17:10 +00005147
Richard Smithfec09922011-11-01 16:57:24 +00005148 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005149 if (Frame) {
5150 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005151 return true;
5152 }
Richard Smithce40ad62011-11-12 22:28:03 +00005153 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005154 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005155
Richard Smith3229b742013-05-05 21:17:10 +00005156 APValue *V;
5157 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005158 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005159 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005160 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005161 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005162 return false;
5163 }
Richard Smith3229b742013-05-05 21:17:10 +00005164 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005165}
5166
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005167bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5168 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005169 // Walk through the expression to find the materialized temporary itself.
5170 SmallVector<const Expr *, 2> CommaLHSs;
5171 SmallVector<SubobjectAdjustment, 2> Adjustments;
5172 const Expr *Inner = E->GetTemporaryExpr()->
5173 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005174
Richard Smith84401042013-06-03 05:03:02 +00005175 // If we passed any comma operators, evaluate their LHSs.
5176 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5177 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5178 return false;
5179
Richard Smithe6c01442013-06-05 00:46:14 +00005180 // A materialized temporary with static storage duration can appear within the
5181 // result of a constant expression evaluation, so we need to preserve its
5182 // value for use outside this evaluation.
5183 APValue *Value;
5184 if (E->getStorageDuration() == SD_Static) {
5185 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005186 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005187 Result.set(E);
5188 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005189 Value = &Info.CurrentCall->
5190 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005191 Result.set(E, Info.CurrentCall->Index);
5192 }
5193
Richard Smithea4ad5d2013-06-06 08:19:16 +00005194 QualType Type = Inner->getType();
5195
Richard Smith84401042013-06-03 05:03:02 +00005196 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005197 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5198 (E->getStorageDuration() == SD_Static &&
5199 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5200 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005201 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005202 }
Richard Smith84401042013-06-03 05:03:02 +00005203
5204 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005205 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5206 --I;
5207 switch (Adjustments[I].Kind) {
5208 case SubobjectAdjustment::DerivedToBaseAdjustment:
5209 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5210 Type, Result))
5211 return false;
5212 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5213 break;
5214
5215 case SubobjectAdjustment::FieldAdjustment:
5216 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5217 return false;
5218 Type = Adjustments[I].Field->getType();
5219 break;
5220
5221 case SubobjectAdjustment::MemberPointerAdjustment:
5222 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5223 Adjustments[I].Ptr.RHS))
5224 return false;
5225 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5226 break;
5227 }
5228 }
5229
5230 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005231}
5232
Peter Collingbournee9200682011-05-13 03:29:01 +00005233bool
5234LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005235 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5236 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005237 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5238 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005239 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005240}
5241
Richard Smith6e525142011-12-27 12:18:28 +00005242bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005243 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005244 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005245
Faisal Valie690b7a2016-07-02 22:34:24 +00005246 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005247 << E->getExprOperand()->getType()
5248 << E->getExprOperand()->getSourceRange();
5249 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005250}
5251
Francois Pichet0066db92012-04-16 04:08:35 +00005252bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5253 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005254}
Francois Pichet0066db92012-04-16 04:08:35 +00005255
Peter Collingbournee9200682011-05-13 03:29:01 +00005256bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005257 // Handle static data members.
5258 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005259 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005260 return VisitVarDecl(E, VD);
5261 }
5262
Richard Smith254a73d2011-10-28 22:34:42 +00005263 // Handle static member functions.
5264 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5265 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005266 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005267 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005268 }
5269 }
5270
Richard Smithd62306a2011-11-10 06:34:14 +00005271 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005272 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005273}
5274
Peter Collingbournee9200682011-05-13 03:29:01 +00005275bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005276 // FIXME: Deal with vectors as array subscript bases.
5277 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005278 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005279
Nick Lewyckyad888682017-04-27 07:27:36 +00005280 bool Success = true;
5281 if (!evaluatePointer(E->getBase(), Result)) {
5282 if (!Info.noteFailure())
5283 return false;
5284 Success = false;
5285 }
Mike Stump11289f42009-09-09 15:08:12 +00005286
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005287 APSInt Index;
5288 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005289 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005290
Nick Lewyckyad888682017-04-27 07:27:36 +00005291 return Success &&
5292 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005293}
Eli Friedman9a156e52008-11-12 09:44:48 +00005294
Peter Collingbournee9200682011-05-13 03:29:01 +00005295bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005296 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005297}
5298
Richard Smith66c96992012-02-18 22:04:06 +00005299bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5300 if (!Visit(E->getSubExpr()))
5301 return false;
5302 // __real is a no-op on scalar lvalues.
5303 if (E->getSubExpr()->getType()->isAnyComplexType())
5304 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5305 return true;
5306}
5307
5308bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5309 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5310 "lvalue __imag__ on scalar?");
5311 if (!Visit(E->getSubExpr()))
5312 return false;
5313 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5314 return true;
5315}
5316
Richard Smith243ef902013-05-05 23:31:59 +00005317bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005318 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005319 return Error(UO);
5320
5321 if (!this->Visit(UO->getSubExpr()))
5322 return false;
5323
Richard Smith243ef902013-05-05 23:31:59 +00005324 return handleIncDec(
5325 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005326 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005327}
5328
5329bool LValueExprEvaluator::VisitCompoundAssignOperator(
5330 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005331 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005332 return Error(CAO);
5333
Richard Smith3229b742013-05-05 21:17:10 +00005334 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005335
5336 // The overall lvalue result is the result of evaluating the LHS.
5337 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005338 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005339 Evaluate(RHS, this->Info, CAO->getRHS());
5340 return false;
5341 }
5342
Richard Smith3229b742013-05-05 21:17:10 +00005343 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5344 return false;
5345
Richard Smith43e77732013-05-07 04:50:00 +00005346 return handleCompoundAssignment(
5347 this->Info, CAO,
5348 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5349 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005350}
5351
5352bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005353 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005354 return Error(E);
5355
Richard Smith3229b742013-05-05 21:17:10 +00005356 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005357
5358 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005359 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005360 Evaluate(NewVal, this->Info, E->getRHS());
5361 return false;
5362 }
5363
Richard Smith3229b742013-05-05 21:17:10 +00005364 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5365 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005366
5367 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005368 NewVal);
5369}
5370
Eli Friedman9a156e52008-11-12 09:44:48 +00005371//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005372// Pointer Evaluation
5373//===----------------------------------------------------------------------===//
5374
George Burgess IVe3763372016-12-22 02:50:20 +00005375/// \brief Attempts to compute the number of bytes available at the pointer
5376/// returned by a function with the alloc_size attribute. Returns true if we
5377/// were successful. Places an unsigned number into `Result`.
5378///
5379/// This expects the given CallExpr to be a call to a function with an
5380/// alloc_size attribute.
5381static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5382 const CallExpr *Call,
5383 llvm::APInt &Result) {
5384 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5385
5386 // alloc_size args are 1-indexed, 0 means not present.
5387 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5388 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5389 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5390 if (Call->getNumArgs() <= SizeArgNo)
5391 return false;
5392
5393 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5394 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5395 return false;
5396 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5397 return false;
5398 Into = Into.zextOrSelf(BitsInSizeT);
5399 return true;
5400 };
5401
5402 APSInt SizeOfElem;
5403 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5404 return false;
5405
5406 if (!AllocSize->getNumElemsParam()) {
5407 Result = std::move(SizeOfElem);
5408 return true;
5409 }
5410
5411 APSInt NumberOfElems;
5412 // Argument numbers start at 1
5413 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5414 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5415 return false;
5416
5417 bool Overflow;
5418 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5419 if (Overflow)
5420 return false;
5421
5422 Result = std::move(BytesAvailable);
5423 return true;
5424}
5425
5426/// \brief Convenience function. LVal's base must be a call to an alloc_size
5427/// function.
5428static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5429 const LValue &LVal,
5430 llvm::APInt &Result) {
5431 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5432 "Can't get the size of a non alloc_size function");
5433 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5434 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5435 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5436}
5437
5438/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5439/// a function with the alloc_size attribute. If it was possible to do so, this
5440/// function will return true, make Result's Base point to said function call,
5441/// and mark Result's Base as invalid.
5442static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5443 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005444 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005445 return false;
5446
5447 // Because we do no form of static analysis, we only support const variables.
5448 //
5449 // Additionally, we can't support parameters, nor can we support static
5450 // variables (in the latter case, use-before-assign isn't UB; in the former,
5451 // we have no clue what they'll be assigned to).
5452 const auto *VD =
5453 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5454 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5455 return false;
5456
5457 const Expr *Init = VD->getAnyInitializer();
5458 if (!Init)
5459 return false;
5460
5461 const Expr *E = Init->IgnoreParens();
5462 if (!tryUnwrapAllocSizeCall(E))
5463 return false;
5464
5465 // Store E instead of E unwrapped so that the type of the LValue's base is
5466 // what the user wanted.
5467 Result.setInvalid(E);
5468
5469 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Daniel Jasperffdee092017-05-02 19:21:42 +00005470 Result.addUnsizedArray(Info, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005471 return true;
5472}
5473
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005474namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005475class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005476 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005477 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005478 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005479
Peter Collingbournee9200682011-05-13 03:29:01 +00005480 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005481 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005482 return true;
5483 }
George Burgess IVe3763372016-12-22 02:50:20 +00005484
George Burgess IVf9013bf2017-02-10 22:52:29 +00005485 bool evaluateLValue(const Expr *E, LValue &Result) {
5486 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5487 }
5488
5489 bool evaluatePointer(const Expr *E, LValue &Result) {
5490 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5491 }
5492
George Burgess IVe3763372016-12-22 02:50:20 +00005493 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005494public:
Mike Stump11289f42009-09-09 15:08:12 +00005495
George Burgess IVf9013bf2017-02-10 22:52:29 +00005496 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5497 : ExprEvaluatorBaseTy(info), Result(Result),
5498 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005499
Richard Smith2e312c82012-03-03 22:46:17 +00005500 bool Success(const APValue &V, const Expr *E) {
5501 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005502 return true;
5503 }
Richard Smithfddd3842011-12-30 21:15:51 +00005504 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005505 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5506 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005507 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005508 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005509
John McCall45d55e42010-05-07 21:00:08 +00005510 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005511 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005512 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005513 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005514 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005515 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5516 if (Info.noteFailure())
5517 EvaluateIgnoredValue(Info, E->getSubExpr());
5518 return Error(E);
5519 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005520 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005521 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005522 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005523 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005524 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005525 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005526 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005527 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005528 }
Richard Smithd62306a2011-11-10 06:34:14 +00005529 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005530 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005531 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005532 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005533 if (!Info.CurrentCall->This) {
5534 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005535 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005536 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005537 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005538 return false;
5539 }
Richard Smithd62306a2011-11-10 06:34:14 +00005540 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005541 // If we are inside a lambda's call operator, the 'this' expression refers
5542 // to the enclosing '*this' object (either by value or reference) which is
5543 // either copied into the closure object's field that represents the '*this'
5544 // or refers to '*this'.
5545 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5546 // Update 'Result' to refer to the data member/field of the closure object
5547 // that represents the '*this' capture.
5548 if (!HandleLValueMember(Info, E, Result,
Daniel Jasperffdee092017-05-02 19:21:42 +00005549 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005550 return false;
5551 // If we captured '*this' by reference, replace the field with its referent.
5552 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5553 ->isPointerType()) {
5554 APValue RVal;
5555 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5556 RVal))
5557 return false;
5558
5559 Result.setFrom(Info.Ctx, RVal);
5560 }
5561 }
Richard Smithd62306a2011-11-10 06:34:14 +00005562 return true;
5563 }
John McCallc07a0c72011-02-17 10:25:35 +00005564
Eli Friedman449fe542009-03-23 04:56:01 +00005565 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005566};
Chris Lattner05706e882008-07-11 18:11:29 +00005567} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005568
George Burgess IVf9013bf2017-02-10 22:52:29 +00005569static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5570 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005571 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005572 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005573}
5574
John McCall45d55e42010-05-07 21:00:08 +00005575bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005576 if (E->getOpcode() != BO_Add &&
5577 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005578 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005579
Chris Lattner05706e882008-07-11 18:11:29 +00005580 const Expr *PExp = E->getLHS();
5581 const Expr *IExp = E->getRHS();
5582 if (IExp->getType()->isPointerType())
5583 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005584
George Burgess IVf9013bf2017-02-10 22:52:29 +00005585 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005586 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005587 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005588
John McCall45d55e42010-05-07 21:00:08 +00005589 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005590 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005591 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005592
Richard Smith96e0c102011-11-04 02:25:55 +00005593 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005594 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005595
Ted Kremenek28831752012-08-23 20:46:57 +00005596 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005597 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005598}
Eli Friedman9a156e52008-11-12 09:44:48 +00005599
John McCall45d55e42010-05-07 21:00:08 +00005600bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005601 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005602}
Mike Stump11289f42009-09-09 15:08:12 +00005603
Peter Collingbournee9200682011-05-13 03:29:01 +00005604bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5605 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005606
Eli Friedman847a2bc2009-12-27 05:43:15 +00005607 switch (E->getCastKind()) {
5608 default:
5609 break;
5610
John McCalle3027922010-08-25 11:45:40 +00005611 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005612 case CK_CPointerToObjCPointerCast:
5613 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005614 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005615 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005616 if (!Visit(SubExpr))
5617 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005618 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5619 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5620 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005621 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005622 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005623 if (SubExpr->getType()->isVoidPointerType())
5624 CCEDiag(E, diag::note_constexpr_invalid_cast)
5625 << 3 << SubExpr->getType();
5626 else
5627 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5628 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005629 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5630 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005631 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005632
Anders Carlsson18275092010-10-31 20:41:46 +00005633 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005634 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005635 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005636 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005637 if (!Result.Base && Result.Offset.isZero())
5638 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005639
Richard Smithd62306a2011-11-10 06:34:14 +00005640 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005641 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005642 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5643 castAs<PointerType>()->getPointeeType(),
5644 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005645
Richard Smith027bf112011-11-17 22:56:20 +00005646 case CK_BaseToDerived:
5647 if (!Visit(E->getSubExpr()))
5648 return false;
5649 if (!Result.Base && Result.Offset.isZero())
5650 return true;
5651 return HandleBaseToDerivedCast(Info, E, Result);
5652
Richard Smith0b0a0b62011-10-29 20:57:55 +00005653 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005654 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005655 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005656
John McCalle3027922010-08-25 11:45:40 +00005657 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005658 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5659
Richard Smith2e312c82012-03-03 22:46:17 +00005660 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005661 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005662 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005663
John McCall45d55e42010-05-07 21:00:08 +00005664 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005665 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5666 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005667 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005668 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005669 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005670 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005671 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005672 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005673 return true;
5674 } else {
5675 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005676 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005677 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005678 }
5679 }
John McCalle3027922010-08-25 11:45:40 +00005680 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005681 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005682 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005683 return false;
5684 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005685 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005686 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005687 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005688 return false;
5689 }
Richard Smith96e0c102011-11-04 02:25:55 +00005690 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005691 if (const ConstantArrayType *CAT
5692 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5693 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005694 else
5695 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005696 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005697
John McCalle3027922010-08-25 11:45:40 +00005698 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005699 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005700
5701 case CK_LValueToRValue: {
5702 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005703 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005704 return false;
5705
5706 APValue RVal;
5707 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5708 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5709 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005710 return InvalidBaseOK &&
5711 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005712 return Success(RVal, E);
5713 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005714 }
5715
Richard Smith11562c52011-10-28 17:51:58 +00005716 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005717}
Chris Lattner05706e882008-07-11 18:11:29 +00005718
Hal Finkel0dd05d42014-10-03 17:18:37 +00005719static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5720 // C++ [expr.alignof]p3:
5721 // When alignof is applied to a reference type, the result is the
5722 // alignment of the referenced type.
5723 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5724 T = Ref->getPointeeType();
5725
5726 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005727 if (T.getQualifiers().hasUnaligned())
5728 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005729 return Info.Ctx.toCharUnitsFromBits(
5730 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5731}
5732
5733static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5734 E = E->IgnoreParens();
5735
5736 // The kinds of expressions that we have special-case logic here for
5737 // should be kept up to date with the special checks for those
5738 // expressions in Sema.
5739
5740 // alignof decl is always accepted, even if it doesn't make sense: we default
5741 // to 1 in those cases.
5742 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5743 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5744 /*RefAsPointee*/true);
5745
5746 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5747 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5748 /*RefAsPointee*/true);
5749
5750 return GetAlignOfType(Info, E->getType());
5751}
5752
George Burgess IVe3763372016-12-22 02:50:20 +00005753// To be clear: this happily visits unsupported builtins. Better name welcomed.
5754bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5755 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5756 return true;
5757
George Burgess IVf9013bf2017-02-10 22:52:29 +00005758 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005759 return false;
5760
5761 Result.setInvalid(E);
5762 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Daniel Jasperffdee092017-05-02 19:21:42 +00005763 Result.addUnsizedArray(Info, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00005764 return true;
5765}
5766
Peter Collingbournee9200682011-05-13 03:29:01 +00005767bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005768 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005769 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005770
Richard Smith6328cbd2016-11-16 00:57:23 +00005771 if (unsigned BuiltinOp = E->getBuiltinCallee())
5772 return VisitBuiltinCallExpr(E, BuiltinOp);
5773
George Burgess IVe3763372016-12-22 02:50:20 +00005774 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005775}
5776
5777bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5778 unsigned BuiltinOp) {
5779 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005780 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005781 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005782 case Builtin::BI__builtin_assume_aligned: {
5783 // We need to be very careful here because: if the pointer does not have the
5784 // asserted alignment, then the behavior is undefined, and undefined
5785 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005786 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005787 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005788
Hal Finkel0dd05d42014-10-03 17:18:37 +00005789 LValue OffsetResult(Result);
5790 APSInt Alignment;
5791 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5792 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005793 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005794
5795 if (E->getNumArgs() > 2) {
5796 APSInt Offset;
5797 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5798 return false;
5799
Richard Smith642a2362017-01-30 23:30:26 +00005800 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005801 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5802 }
5803
5804 // If there is a base object, then it must have the correct alignment.
5805 if (OffsetResult.Base) {
5806 CharUnits BaseAlignment;
5807 if (const ValueDecl *VD =
5808 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5809 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5810 } else {
5811 BaseAlignment =
5812 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5813 }
5814
5815 if (BaseAlignment < Align) {
5816 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005817 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005818 CCEDiag(E->getArg(0),
5819 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005820 << (unsigned)BaseAlignment.getQuantity()
5821 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005822 return false;
5823 }
5824 }
5825
5826 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005827 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005828 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005829
Richard Smith642a2362017-01-30 23:30:26 +00005830 (OffsetResult.Base
5831 ? CCEDiag(E->getArg(0),
5832 diag::note_constexpr_baa_insufficient_alignment) << 1
5833 : CCEDiag(E->getArg(0),
5834 diag::note_constexpr_baa_value_insufficient_alignment))
5835 << (int)OffsetResult.Offset.getQuantity()
5836 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005837 return false;
5838 }
5839
5840 return true;
5841 }
Richard Smithe9507952016-11-12 01:39:56 +00005842
5843 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005844 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005845 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005846 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005847 if (Info.getLangOpts().CPlusPlus11)
5848 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5849 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005850 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005851 else
5852 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5853 // Fall through.
5854 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005855 case Builtin::BI__builtin_wcschr:
5856 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005857 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005858 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005859 if (!Visit(E->getArg(0)))
5860 return false;
5861 APSInt Desired;
5862 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5863 return false;
5864 uint64_t MaxLength = uint64_t(-1);
5865 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005866 BuiltinOp != Builtin::BIwcschr &&
5867 BuiltinOp != Builtin::BI__builtin_strchr &&
5868 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005869 APSInt N;
5870 if (!EvaluateInteger(E->getArg(2), N, Info))
5871 return false;
5872 MaxLength = N.getExtValue();
5873 }
5874
Richard Smith8110c9d2016-11-29 19:45:17 +00005875 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005876
Richard Smith8110c9d2016-11-29 19:45:17 +00005877 // Figure out what value we're actually looking for (after converting to
5878 // the corresponding unsigned type if necessary).
5879 uint64_t DesiredVal;
5880 bool StopAtNull = false;
5881 switch (BuiltinOp) {
5882 case Builtin::BIstrchr:
5883 case Builtin::BI__builtin_strchr:
5884 // strchr compares directly to the passed integer, and therefore
5885 // always fails if given an int that is not a char.
5886 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5887 E->getArg(1)->getType(),
5888 Desired),
5889 Desired))
5890 return ZeroInitialization(E);
5891 StopAtNull = true;
5892 // Fall through.
5893 case Builtin::BImemchr:
5894 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005895 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005896 // memchr compares by converting both sides to unsigned char. That's also
5897 // correct for strchr if we get this far (to cope with plain char being
5898 // unsigned in the strchr case).
5899 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5900 break;
Richard Smithe9507952016-11-12 01:39:56 +00005901
Richard Smith8110c9d2016-11-29 19:45:17 +00005902 case Builtin::BIwcschr:
5903 case Builtin::BI__builtin_wcschr:
5904 StopAtNull = true;
5905 // Fall through.
5906 case Builtin::BIwmemchr:
5907 case Builtin::BI__builtin_wmemchr:
5908 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5909 DesiredVal = Desired.getZExtValue();
5910 break;
5911 }
Richard Smithe9507952016-11-12 01:39:56 +00005912
5913 for (; MaxLength; --MaxLength) {
5914 APValue Char;
5915 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5916 !Char.isInt())
5917 return false;
5918 if (Char.getInt().getZExtValue() == DesiredVal)
5919 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005920 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005921 break;
5922 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5923 return false;
5924 }
5925 // Not found: return nullptr.
5926 return ZeroInitialization(E);
5927 }
5928
Richard Smith6cbd65d2013-07-11 02:27:57 +00005929 default:
George Burgess IVe3763372016-12-22 02:50:20 +00005930 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005931 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005932}
Chris Lattner05706e882008-07-11 18:11:29 +00005933
5934//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005935// Member Pointer Evaluation
5936//===----------------------------------------------------------------------===//
5937
5938namespace {
5939class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005940 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005941 MemberPtr &Result;
5942
5943 bool Success(const ValueDecl *D) {
5944 Result = MemberPtr(D);
5945 return true;
5946 }
5947public:
5948
5949 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5950 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5951
Richard Smith2e312c82012-03-03 22:46:17 +00005952 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005953 Result.setFrom(V);
5954 return true;
5955 }
Richard Smithfddd3842011-12-30 21:15:51 +00005956 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005957 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005958 }
5959
5960 bool VisitCastExpr(const CastExpr *E);
5961 bool VisitUnaryAddrOf(const UnaryOperator *E);
5962};
5963} // end anonymous namespace
5964
5965static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5966 EvalInfo &Info) {
5967 assert(E->isRValue() && E->getType()->isMemberPointerType());
5968 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5969}
5970
5971bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5972 switch (E->getCastKind()) {
5973 default:
5974 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5975
5976 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005977 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005978 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005979
5980 case CK_BaseToDerivedMemberPointer: {
5981 if (!Visit(E->getSubExpr()))
5982 return false;
5983 if (E->path_empty())
5984 return true;
5985 // Base-to-derived member pointer casts store the path in derived-to-base
5986 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5987 // the wrong end of the derived->base arc, so stagger the path by one class.
5988 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5989 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5990 PathI != PathE; ++PathI) {
5991 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5992 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5993 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005994 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005995 }
5996 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5997 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005998 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005999 return true;
6000 }
6001
6002 case CK_DerivedToBaseMemberPointer:
6003 if (!Visit(E->getSubExpr()))
6004 return false;
6005 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6006 PathE = E->path_end(); PathI != PathE; ++PathI) {
6007 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6008 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6009 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006010 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006011 }
6012 return true;
6013 }
6014}
6015
6016bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6017 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6018 // member can be formed.
6019 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6020}
6021
6022//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006023// Record Evaluation
6024//===----------------------------------------------------------------------===//
6025
6026namespace {
6027 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006028 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006029 const LValue &This;
6030 APValue &Result;
6031 public:
6032
6033 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6034 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6035
Richard Smith2e312c82012-03-03 22:46:17 +00006036 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006037 Result = V;
6038 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006039 }
Richard Smithb8348f52016-05-12 22:16:28 +00006040 bool ZeroInitialization(const Expr *E) {
6041 return ZeroInitialization(E, E->getType());
6042 }
6043 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006044
Richard Smith52a980a2015-08-28 02:43:42 +00006045 bool VisitCallExpr(const CallExpr *E) {
6046 return handleCallExpr(E, Result, &This);
6047 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006048 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006049 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006050 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6051 return VisitCXXConstructExpr(E, E->getType());
6052 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006053 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006054 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006055 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006056 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006057 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006058}
Richard Smithd62306a2011-11-10 06:34:14 +00006059
Richard Smithfddd3842011-12-30 21:15:51 +00006060/// Perform zero-initialization on an object of non-union class type.
6061/// C++11 [dcl.init]p5:
6062/// To zero-initialize an object or reference of type T means:
6063/// [...]
6064/// -- if T is a (possibly cv-qualified) non-union class type,
6065/// each non-static data member and each base-class subobject is
6066/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006067static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6068 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006069 const LValue &This, APValue &Result) {
6070 assert(!RD->isUnion() && "Expected non-union class type");
6071 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6072 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006073 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006074
John McCalld7bca762012-05-01 00:38:49 +00006075 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006076 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6077
6078 if (CD) {
6079 unsigned Index = 0;
6080 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006081 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006082 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6083 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006084 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6085 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006086 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006087 Result.getStructBase(Index)))
6088 return false;
6089 }
6090 }
6091
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006092 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006093 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006094 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006095 continue;
6096
6097 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006098 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006099 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006100
David Blaikie2d7c57e2012-04-30 02:36:29 +00006101 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006102 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006103 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006104 return false;
6105 }
6106
6107 return true;
6108}
6109
Richard Smithb8348f52016-05-12 22:16:28 +00006110bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6111 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006112 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006113 if (RD->isUnion()) {
6114 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6115 // object's first non-static named data member is zero-initialized
6116 RecordDecl::field_iterator I = RD->field_begin();
6117 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006118 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006119 return true;
6120 }
6121
6122 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006123 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006124 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006125 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006126 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006127 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006128 }
6129
Richard Smith5d108602012-02-17 00:44:16 +00006130 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006131 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006132 return false;
6133 }
6134
Richard Smitha8105bc2012-01-06 16:39:00 +00006135 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006136}
6137
Richard Smithe97cbd72011-11-11 04:05:33 +00006138bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6139 switch (E->getCastKind()) {
6140 default:
6141 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6142
6143 case CK_ConstructorConversion:
6144 return Visit(E->getSubExpr());
6145
6146 case CK_DerivedToBase:
6147 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006148 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006149 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006150 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006151 if (!DerivedObject.isStruct())
6152 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006153
6154 // Derived-to-base rvalue conversion: just slice off the derived part.
6155 APValue *Value = &DerivedObject;
6156 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6157 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6158 PathE = E->path_end(); PathI != PathE; ++PathI) {
6159 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6160 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6161 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6162 RD = Base;
6163 }
6164 Result = *Value;
6165 return true;
6166 }
6167 }
6168}
6169
Richard Smithd62306a2011-11-10 06:34:14 +00006170bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006171 if (E->isTransparent())
6172 return Visit(E->getInit(0));
6173
Richard Smithd62306a2011-11-10 06:34:14 +00006174 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006175 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006176 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6177
6178 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006179 const FieldDecl *Field = E->getInitializedFieldInUnion();
6180 Result = APValue(Field);
6181 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006182 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006183
6184 // If the initializer list for a union does not contain any elements, the
6185 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006186 // FIXME: The element should be initialized from an initializer list.
6187 // Is this difference ever observable for initializer lists which
6188 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006189 ImplicitValueInitExpr VIE(Field->getType());
6190 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6191
Richard Smithd62306a2011-11-10 06:34:14 +00006192 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006193 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6194 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006195
6196 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6197 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6198 isa<CXXDefaultInitExpr>(InitExpr));
6199
Richard Smithb228a862012-02-15 02:18:13 +00006200 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006201 }
6202
Richard Smith872307e2016-03-08 22:17:41 +00006203 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006204 if (Result.isUninit())
6205 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6206 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006207 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006208 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006209
6210 // Initialize base classes.
6211 if (CXXRD) {
6212 for (const auto &Base : CXXRD->bases()) {
6213 assert(ElementNo < E->getNumInits() && "missing init for base class");
6214 const Expr *Init = E->getInit(ElementNo);
6215
6216 LValue Subobject = This;
6217 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6218 return false;
6219
6220 APValue &FieldVal = Result.getStructBase(ElementNo);
6221 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006222 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006223 return false;
6224 Success = false;
6225 }
6226 ++ElementNo;
6227 }
6228 }
6229
6230 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006231 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006232 // Anonymous bit-fields are not considered members of the class for
6233 // purposes of aggregate initialization.
6234 if (Field->isUnnamedBitfield())
6235 continue;
6236
6237 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006238
Richard Smith253c2a32012-01-27 01:14:48 +00006239 bool HaveInit = ElementNo < E->getNumInits();
6240
6241 // FIXME: Diagnostics here should point to the end of the initializer
6242 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006243 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006244 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006245 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006246
6247 // Perform an implicit value-initialization for members beyond the end of
6248 // the initializer list.
6249 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006250 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Nick Lewyckye7d6fbd2017-04-29 09:33:46 +00006251 if (Init->isValueDependent()) {
6252 Success = false;
6253 continue;
6254 }
Richard Smith253c2a32012-01-27 01:14:48 +00006255
Richard Smith852c9db2013-04-20 22:23:05 +00006256 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6257 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6258 isa<CXXDefaultInitExpr>(Init));
6259
Richard Smith49ca8aa2013-08-06 07:09:20 +00006260 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6261 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6262 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006263 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006264 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006265 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006266 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006267 }
6268 }
6269
Richard Smith253c2a32012-01-27 01:14:48 +00006270 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006271}
6272
Richard Smithb8348f52016-05-12 22:16:28 +00006273bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6274 QualType T) {
6275 // Note that E's type is not necessarily the type of our class here; we might
6276 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006277 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006278 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6279
Richard Smithfddd3842011-12-30 21:15:51 +00006280 bool ZeroInit = E->requiresZeroInitialization();
6281 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006282 // If we've already performed zero-initialization, we're already done.
6283 if (!Result.isUninit())
6284 return true;
6285
Richard Smithda3f4fd2014-03-05 23:32:50 +00006286 // We can get here in two different ways:
6287 // 1) We're performing value-initialization, and should zero-initialize
6288 // the object, or
6289 // 2) We're performing default-initialization of an object with a trivial
6290 // constexpr default constructor, in which case we should start the
6291 // lifetimes of all the base subobjects (there can be no data member
6292 // subobjects in this case) per [basic.life]p1.
6293 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006294 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006295 }
6296
Craig Topper36250ad2014-05-12 05:36:57 +00006297 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006298 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006299
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006300 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006301 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006302
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006303 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006304 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006305 if (const MaterializeTemporaryExpr *ME
6306 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6307 return Visit(ME->GetTemporaryExpr());
6308
Richard Smithb8348f52016-05-12 22:16:28 +00006309 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006310 return false;
6311
Craig Topper5fc8fc22014-08-27 06:28:36 +00006312 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006313 return HandleConstructorCall(E, This, Args,
6314 cast<CXXConstructorDecl>(Definition), Info,
6315 Result);
6316}
6317
6318bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6319 const CXXInheritedCtorInitExpr *E) {
6320 if (!Info.CurrentCall) {
6321 assert(Info.checkingPotentialConstantExpression());
6322 return false;
6323 }
6324
6325 const CXXConstructorDecl *FD = E->getConstructor();
6326 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6327 return false;
6328
6329 const FunctionDecl *Definition = nullptr;
6330 auto Body = FD->getBody(Definition);
6331
6332 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6333 return false;
6334
6335 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006336 cast<CXXConstructorDecl>(Definition), Info,
6337 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006338}
6339
Richard Smithcc1b96d2013-06-12 22:31:48 +00006340bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6341 const CXXStdInitializerListExpr *E) {
6342 const ConstantArrayType *ArrayType =
6343 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6344
6345 LValue Array;
6346 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6347 return false;
6348
6349 // Get a pointer to the first element of the array.
6350 Array.addArray(Info, E, ArrayType);
6351
6352 // FIXME: Perform the checks on the field types in SemaInit.
6353 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6354 RecordDecl::field_iterator Field = Record->field_begin();
6355 if (Field == Record->field_end())
6356 return Error(E);
6357
6358 // Start pointer.
6359 if (!Field->getType()->isPointerType() ||
6360 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6361 ArrayType->getElementType()))
6362 return Error(E);
6363
6364 // FIXME: What if the initializer_list type has base classes, etc?
6365 Result = APValue(APValue::UninitStruct(), 0, 2);
6366 Array.moveInto(Result.getStructField(0));
6367
6368 if (++Field == Record->field_end())
6369 return Error(E);
6370
6371 if (Field->getType()->isPointerType() &&
6372 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6373 ArrayType->getElementType())) {
6374 // End pointer.
6375 if (!HandleLValueArrayAdjustment(Info, E, Array,
6376 ArrayType->getElementType(),
6377 ArrayType->getSize().getZExtValue()))
6378 return false;
6379 Array.moveInto(Result.getStructField(1));
6380 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6381 // Length.
6382 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6383 else
6384 return Error(E);
6385
6386 if (++Field != Record->field_end())
6387 return Error(E);
6388
6389 return true;
6390}
6391
Faisal Valic72a08c2017-01-09 03:02:53 +00006392bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6393 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6394 if (ClosureClass->isInvalidDecl()) return false;
6395
6396 if (Info.checkingPotentialConstantExpression()) return true;
Daniel Jasperffdee092017-05-02 19:21:42 +00006397
Faisal Vali051e3a22017-02-16 04:12:21 +00006398 const size_t NumFields =
6399 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006400
6401 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6402 E->capture_init_end()) &&
6403 "The number of lambda capture initializers should equal the number of "
6404 "fields within the closure type");
6405
Faisal Vali051e3a22017-02-16 04:12:21 +00006406 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6407 // Iterate through all the lambda's closure object's fields and initialize
6408 // them.
6409 auto *CaptureInitIt = E->capture_init_begin();
6410 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6411 bool Success = true;
6412 for (const auto *Field : ClosureClass->fields()) {
6413 assert(CaptureInitIt != E->capture_init_end());
6414 // Get the initializer for this field
6415 Expr *const CurFieldInit = *CaptureInitIt++;
Daniel Jasperffdee092017-05-02 19:21:42 +00006416
Faisal Vali051e3a22017-02-16 04:12:21 +00006417 // If there is no initializer, either this is a VLA or an error has
6418 // occurred.
6419 if (!CurFieldInit)
6420 return Error(E);
6421
6422 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6423 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6424 if (!Info.keepEvaluatingAfterFailure())
6425 return false;
6426 Success = false;
6427 }
6428 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006429 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006430 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006431}
6432
Richard Smithd62306a2011-11-10 06:34:14 +00006433static bool EvaluateRecord(const Expr *E, const LValue &This,
6434 APValue &Result, EvalInfo &Info) {
6435 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006436 "can't evaluate expression as a record rvalue");
6437 return RecordExprEvaluator(Info, This, Result).Visit(E);
6438}
6439
6440//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006441// Temporary Evaluation
6442//
6443// Temporaries are represented in the AST as rvalues, but generally behave like
6444// lvalues. The full-object of which the temporary is a subobject is implicitly
6445// materialized so that a reference can bind to it.
6446//===----------------------------------------------------------------------===//
6447namespace {
6448class TemporaryExprEvaluator
6449 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6450public:
6451 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006452 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006453
6454 /// Visit an expression which constructs the value of this temporary.
6455 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006456 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006457 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6458 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006459 }
6460
6461 bool VisitCastExpr(const CastExpr *E) {
6462 switch (E->getCastKind()) {
6463 default:
6464 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6465
6466 case CK_ConstructorConversion:
6467 return VisitConstructExpr(E->getSubExpr());
6468 }
6469 }
6470 bool VisitInitListExpr(const InitListExpr *E) {
6471 return VisitConstructExpr(E);
6472 }
6473 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6474 return VisitConstructExpr(E);
6475 }
6476 bool VisitCallExpr(const CallExpr *E) {
6477 return VisitConstructExpr(E);
6478 }
Richard Smith513955c2014-12-17 19:24:30 +00006479 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6480 return VisitConstructExpr(E);
6481 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006482 bool VisitLambdaExpr(const LambdaExpr *E) {
6483 return VisitConstructExpr(E);
6484 }
Richard Smith027bf112011-11-17 22:56:20 +00006485};
6486} // end anonymous namespace
6487
6488/// Evaluate an expression of record type as a temporary.
6489static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006490 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006491 return TemporaryExprEvaluator(Info, Result).Visit(E);
6492}
6493
6494//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006495// Vector Evaluation
6496//===----------------------------------------------------------------------===//
6497
6498namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006499 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006500 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006501 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006502 public:
Mike Stump11289f42009-09-09 15:08:12 +00006503
Richard Smith2d406342011-10-22 21:10:00 +00006504 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6505 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006506
Craig Topper9798b932015-09-29 04:30:05 +00006507 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006508 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6509 // FIXME: remove this APValue copy.
6510 Result = APValue(V.data(), V.size());
6511 return true;
6512 }
Richard Smith2e312c82012-03-03 22:46:17 +00006513 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006514 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006515 Result = V;
6516 return true;
6517 }
Richard Smithfddd3842011-12-30 21:15:51 +00006518 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006519
Richard Smith2d406342011-10-22 21:10:00 +00006520 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006521 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006522 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006523 bool VisitInitListExpr(const InitListExpr *E);
6524 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006525 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006526 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006527 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006528 };
6529} // end anonymous namespace
6530
6531static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006532 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006533 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006534}
6535
George Burgess IV533ff002015-12-11 00:23:35 +00006536bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006537 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006538 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006539
Richard Smith161f09a2011-12-06 22:44:34 +00006540 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006541 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006542
Eli Friedmanc757de22011-03-25 00:43:55 +00006543 switch (E->getCastKind()) {
6544 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006545 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006546 if (SETy->isIntegerType()) {
6547 APSInt IntResult;
6548 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006549 return false;
6550 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006551 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006552 APFloat FloatResult(0.0);
6553 if (!EvaluateFloat(SE, FloatResult, Info))
6554 return false;
6555 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006556 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006557 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006558 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006559
6560 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006561 SmallVector<APValue, 4> Elts(NElts, Val);
6562 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006563 }
Eli Friedman803acb32011-12-22 03:51:45 +00006564 case CK_BitCast: {
6565 // Evaluate the operand into an APInt we can extract from.
6566 llvm::APInt SValInt;
6567 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6568 return false;
6569 // Extract the elements
6570 QualType EltTy = VTy->getElementType();
6571 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6572 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6573 SmallVector<APValue, 4> Elts;
6574 if (EltTy->isRealFloatingType()) {
6575 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006576 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006577 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006578 FloatEltSize = 80;
6579 for (unsigned i = 0; i < NElts; i++) {
6580 llvm::APInt Elt;
6581 if (BigEndian)
6582 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6583 else
6584 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006585 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006586 }
6587 } else if (EltTy->isIntegerType()) {
6588 for (unsigned i = 0; i < NElts; i++) {
6589 llvm::APInt Elt;
6590 if (BigEndian)
6591 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6592 else
6593 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6594 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6595 }
6596 } else {
6597 return Error(E);
6598 }
6599 return Success(Elts, E);
6600 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006601 default:
Richard Smith11562c52011-10-28 17:51:58 +00006602 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006603 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006604}
6605
Richard Smith2d406342011-10-22 21:10:00 +00006606bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006607VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006608 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006609 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006610 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006611
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006612 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006613 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006614
Eli Friedmanb9c71292012-01-03 23:24:20 +00006615 // The number of initializers can be less than the number of
6616 // vector elements. For OpenCL, this can be due to nested vector
Daniel Jasperffdee092017-05-02 19:21:42 +00006617 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00006618 // should be initialized with zeroes.
6619 unsigned CountInits = 0, CountElts = 0;
6620 while (CountElts < NumElements) {
6621 // Handle nested vector initialization.
Daniel Jasperffdee092017-05-02 19:21:42 +00006622 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006623 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006624 APValue v;
6625 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6626 return Error(E);
6627 unsigned vlen = v.getVectorLength();
Daniel Jasperffdee092017-05-02 19:21:42 +00006628 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00006629 Elements.push_back(v.getVectorElt(j));
6630 CountElts += vlen;
6631 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006632 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006633 if (CountInits < NumInits) {
6634 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006635 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006636 } else // trailing integer zero.
6637 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6638 Elements.push_back(APValue(sInt));
6639 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006640 } else {
6641 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006642 if (CountInits < NumInits) {
6643 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006644 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006645 } else // trailing float zero.
6646 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6647 Elements.push_back(APValue(f));
6648 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006649 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006650 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006651 }
Richard Smith2d406342011-10-22 21:10:00 +00006652 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006653}
6654
Richard Smith2d406342011-10-22 21:10:00 +00006655bool
Richard Smithfddd3842011-12-30 21:15:51 +00006656VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006657 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006658 QualType EltTy = VT->getElementType();
6659 APValue ZeroElement;
6660 if (EltTy->isIntegerType())
6661 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6662 else
6663 ZeroElement =
6664 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6665
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006666 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006667 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006668}
6669
Richard Smith2d406342011-10-22 21:10:00 +00006670bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006671 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006672 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006673}
6674
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006675//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006676// Array Evaluation
6677//===----------------------------------------------------------------------===//
6678
6679namespace {
6680 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006681 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006682 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006683 APValue &Result;
6684 public:
6685
Richard Smithd62306a2011-11-10 06:34:14 +00006686 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6687 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006688
6689 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006690 assert((V.isArray() || V.isLValue()) &&
6691 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006692 Result = V;
6693 return true;
6694 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006695
Richard Smithfddd3842011-12-30 21:15:51 +00006696 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006697 const ConstantArrayType *CAT =
6698 Info.Ctx.getAsConstantArrayType(E->getType());
6699 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006700 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006701
6702 Result = APValue(APValue::UninitArray(), 0,
6703 CAT->getSize().getZExtValue());
6704 if (!Result.hasArrayFiller()) return true;
6705
Richard Smithfddd3842011-12-30 21:15:51 +00006706 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006707 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006708 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006709 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006710 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006711 }
6712
Richard Smith52a980a2015-08-28 02:43:42 +00006713 bool VisitCallExpr(const CallExpr *E) {
6714 return handleCallExpr(E, Result, &This);
6715 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006716 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006717 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006718 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006719 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6720 const LValue &Subobject,
6721 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006722 };
6723} // end anonymous namespace
6724
Richard Smithd62306a2011-11-10 06:34:14 +00006725static bool EvaluateArray(const Expr *E, const LValue &This,
6726 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006727 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006728 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006729}
6730
6731bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6732 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6733 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006734 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006735
Richard Smithca2cfbf2011-12-22 01:07:19 +00006736 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6737 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006738 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006739 LValue LV;
6740 if (!EvaluateLValue(E->getInit(0), LV, Info))
6741 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006742 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006743 LV.moveInto(Val);
6744 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006745 }
6746
Richard Smith253c2a32012-01-27 01:14:48 +00006747 bool Success = true;
6748
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006749 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6750 "zero-initialized array shouldn't have any initialized elts");
6751 APValue Filler;
6752 if (Result.isArray() && Result.hasArrayFiller())
6753 Filler = Result.getArrayFiller();
6754
Richard Smith9543c5e2013-04-22 14:44:29 +00006755 unsigned NumEltsToInit = E->getNumInits();
6756 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006757 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006758
6759 // If the initializer might depend on the array index, run it for each
6760 // array element. For now, just whitelist non-class value-initialization.
6761 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6762 NumEltsToInit = NumElts;
6763
6764 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006765
6766 // If the array was previously zero-initialized, preserve the
6767 // zero-initialized values.
6768 if (!Filler.isUninit()) {
6769 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6770 Result.getArrayInitializedElt(I) = Filler;
6771 if (Result.hasArrayFiller())
6772 Result.getArrayFiller() = Filler;
6773 }
6774
Richard Smithd62306a2011-11-10 06:34:14 +00006775 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006776 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006777 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6778 const Expr *Init =
6779 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006780 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006781 Info, Subobject, Init) ||
6782 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006783 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006784 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006785 return false;
6786 Success = false;
6787 }
Richard Smithd62306a2011-11-10 06:34:14 +00006788 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006789
Richard Smith9543c5e2013-04-22 14:44:29 +00006790 if (!Result.hasArrayFiller())
6791 return Success;
6792
6793 // If we get here, we have a trivial filler, which we can just evaluate
6794 // once and splat over the rest of the array elements.
6795 assert(FillerExpr && "no array filler for incomplete init list");
6796 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6797 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006798}
6799
Richard Smith410306b2016-12-12 02:53:20 +00006800bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6801 if (E->getCommonExpr() &&
6802 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6803 Info, E->getCommonExpr()->getSourceExpr()))
6804 return false;
6805
6806 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6807
6808 uint64_t Elements = CAT->getSize().getZExtValue();
6809 Result = APValue(APValue::UninitArray(), Elements, Elements);
6810
6811 LValue Subobject = This;
6812 Subobject.addArray(Info, E, CAT);
6813
6814 bool Success = true;
6815 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6816 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6817 Info, Subobject, E->getSubExpr()) ||
6818 !HandleLValueArrayAdjustment(Info, E, Subobject,
6819 CAT->getElementType(), 1)) {
6820 if (!Info.noteFailure())
6821 return false;
6822 Success = false;
6823 }
6824 }
6825
6826 return Success;
6827}
6828
Richard Smith027bf112011-11-17 22:56:20 +00006829bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006830 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6831}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006832
Richard Smith9543c5e2013-04-22 14:44:29 +00006833bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6834 const LValue &Subobject,
6835 APValue *Value,
6836 QualType Type) {
6837 bool HadZeroInit = !Value->isUninit();
6838
6839 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6840 unsigned N = CAT->getSize().getZExtValue();
6841
6842 // Preserve the array filler if we had prior zero-initialization.
6843 APValue Filler =
6844 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6845 : APValue();
6846
6847 *Value = APValue(APValue::UninitArray(), N, N);
6848
6849 if (HadZeroInit)
6850 for (unsigned I = 0; I != N; ++I)
6851 Value->getArrayInitializedElt(I) = Filler;
6852
6853 // Initialize the elements.
6854 LValue ArrayElt = Subobject;
6855 ArrayElt.addArray(Info, E, CAT);
6856 for (unsigned I = 0; I != N; ++I)
6857 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6858 CAT->getElementType()) ||
6859 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6860 CAT->getElementType(), 1))
6861 return false;
6862
6863 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006864 }
Richard Smith027bf112011-11-17 22:56:20 +00006865
Richard Smith9543c5e2013-04-22 14:44:29 +00006866 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006867 return Error(E);
6868
Richard Smithb8348f52016-05-12 22:16:28 +00006869 return RecordExprEvaluator(Info, Subobject, *Value)
6870 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006871}
6872
Richard Smithf3e9e432011-11-07 09:22:26 +00006873//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006874// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006875//
6876// As a GNU extension, we support casting pointers to sufficiently-wide integer
6877// types and back in constant folding. Integer values are thus represented
6878// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006879//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006880
6881namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006882class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006883 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006884 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006885public:
Richard Smith2e312c82012-03-03 22:46:17 +00006886 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006887 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006888
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006889 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006890 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006891 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006892 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006893 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006894 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006895 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006896 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006897 return true;
6898 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006899 bool Success(const llvm::APSInt &SI, const Expr *E) {
6900 return Success(SI, E, Result);
6901 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006902
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006903 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00006904 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006905 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006906 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006907 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006908 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006909 Result.getInt().setIsUnsigned(
6910 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006911 return true;
6912 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006913 bool Success(const llvm::APInt &I, const Expr *E) {
6914 return Success(I, E, Result);
6915 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006916
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006917 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00006918 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006919 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006920 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006921 return true;
6922 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006923 bool Success(uint64_t Value, const Expr *E) {
6924 return Success(Value, E, Result);
6925 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006926
Ken Dyckdbc01912011-03-11 02:13:43 +00006927 bool Success(CharUnits Size, const Expr *E) {
6928 return Success(Size.getQuantity(), E);
6929 }
6930
Richard Smith2e312c82012-03-03 22:46:17 +00006931 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006932 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006933 Result = V;
6934 return true;
6935 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006936 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006937 }
Mike Stump11289f42009-09-09 15:08:12 +00006938
Richard Smithfddd3842011-12-30 21:15:51 +00006939 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006940
Peter Collingbournee9200682011-05-13 03:29:01 +00006941 //===--------------------------------------------------------------------===//
6942 // Visitor Methods
6943 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006944
Chris Lattner7174bf32008-07-12 00:38:25 +00006945 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006946 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006947 }
6948 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006949 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006950 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006951
6952 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6953 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006954 if (CheckReferencedDecl(E, E->getDecl()))
6955 return true;
6956
6957 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006958 }
6959 bool VisitMemberExpr(const MemberExpr *E) {
6960 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006961 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006962 return true;
6963 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006964
6965 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006966 }
6967
Peter Collingbournee9200682011-05-13 03:29:01 +00006968 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006969 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006970 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006971 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006972 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006973
Peter Collingbournee9200682011-05-13 03:29:01 +00006974 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006975 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006976
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006977 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006978 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006979 }
Mike Stump11289f42009-09-09 15:08:12 +00006980
Ted Kremeneke65b0862012-03-06 20:05:56 +00006981 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6982 return Success(E->getValue(), E);
6983 }
Richard Smith410306b2016-12-12 02:53:20 +00006984
6985 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6986 if (Info.ArrayInitIndex == uint64_t(-1)) {
6987 // We were asked to evaluate this subexpression independent of the
6988 // enclosing ArrayInitLoopExpr. We can't do that.
6989 Info.FFDiag(E);
6990 return false;
6991 }
6992 return Success(Info.ArrayInitIndex, E);
6993 }
Daniel Jasperffdee092017-05-02 19:21:42 +00006994
Richard Smith4ce706a2011-10-11 21:43:33 +00006995 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006996 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006997 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006998 }
6999
Douglas Gregor29c42f22012-02-24 07:38:34 +00007000 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7001 return Success(E->getValue(), E);
7002 }
7003
John Wiegley6242b6a2011-04-28 00:16:57 +00007004 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7005 return Success(E->getValue(), E);
7006 }
7007
John Wiegleyf9f65842011-04-25 06:54:41 +00007008 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7009 return Success(E->getValue(), E);
7010 }
7011
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007012 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007013 bool VisitUnaryImag(const UnaryOperator *E);
7014
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007015 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007016 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007017
Eli Friedman4e7a2412009-02-27 04:45:43 +00007018 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007019};
Chris Lattner05706e882008-07-11 18:11:29 +00007020} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007021
Richard Smith11562c52011-10-28 17:51:58 +00007022/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7023/// produce either the integer value or a pointer.
7024///
7025/// GCC has a heinous extension which folds casts between pointer types and
7026/// pointer-sized integral types. We support this by allowing the evaluation of
7027/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7028/// Some simple arithmetic on such values is supported (they are treated much
7029/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007030static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007031 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007032 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007033 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007034}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007035
Richard Smithf57d8cb2011-12-09 22:58:01 +00007036static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007037 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007038 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007039 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007040 if (!Val.isInt()) {
7041 // FIXME: It would be better to produce the diagnostic for casting
7042 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007043 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007044 return false;
7045 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007046 Result = Val.getInt();
7047 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007048}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007049
Richard Smithf57d8cb2011-12-09 22:58:01 +00007050/// Check whether the given declaration can be directly converted to an integral
7051/// rvalue. If not, no diagnostic is produced; there are other things we can
7052/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007053bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007054 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007055 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007056 // Check for signedness/width mismatches between E type and ECD value.
7057 bool SameSign = (ECD->getInitVal().isSigned()
7058 == E->getType()->isSignedIntegerOrEnumerationType());
7059 bool SameWidth = (ECD->getInitVal().getBitWidth()
7060 == Info.Ctx.getIntWidth(E->getType()));
7061 if (SameSign && SameWidth)
7062 return Success(ECD->getInitVal(), E);
7063 else {
7064 // Get rid of mismatch (otherwise Success assertions will fail)
7065 // by computing a new value matching the type of E.
7066 llvm::APSInt Val = ECD->getInitVal();
7067 if (!SameSign)
7068 Val.setIsSigned(!ECD->getInitVal().isSigned());
7069 if (!SameWidth)
7070 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7071 return Success(Val, E);
7072 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007073 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007074 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007075}
7076
Chris Lattner86ee2862008-10-06 06:40:35 +00007077/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7078/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007079static int EvaluateBuiltinClassifyType(const CallExpr *E,
7080 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007081 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007082 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007083 enum gcc_type_class {
7084 no_type_class = -1,
7085 void_type_class, integer_type_class, char_type_class,
7086 enumeral_type_class, boolean_type_class,
7087 pointer_type_class, reference_type_class, offset_type_class,
7088 real_type_class, complex_type_class,
7089 function_type_class, method_type_class,
7090 record_type_class, union_type_class,
7091 array_type_class, string_type_class,
7092 lang_type_class
7093 };
Mike Stump11289f42009-09-09 15:08:12 +00007094
7095 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007096 // ideal, however it is what gcc does.
7097 if (E->getNumArgs() == 0)
7098 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007099
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007100 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7101 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7102
7103 switch (CanTy->getTypeClass()) {
7104#define TYPE(ID, BASE)
7105#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7106#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7107#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7108#include "clang/AST/TypeNodes.def"
7109 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7110
7111 case Type::Builtin:
7112 switch (BT->getKind()) {
7113#define BUILTIN_TYPE(ID, SINGLETON_ID)
7114#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7115#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7116#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7117#include "clang/AST/BuiltinTypes.def"
7118 case BuiltinType::Void:
7119 return void_type_class;
7120
7121 case BuiltinType::Bool:
7122 return boolean_type_class;
7123
7124 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7125 case BuiltinType::UChar:
7126 case BuiltinType::UShort:
7127 case BuiltinType::UInt:
7128 case BuiltinType::ULong:
7129 case BuiltinType::ULongLong:
7130 case BuiltinType::UInt128:
7131 return integer_type_class;
7132
7133 case BuiltinType::NullPtr:
7134 return pointer_type_class;
7135
7136 case BuiltinType::WChar_U:
7137 case BuiltinType::Char16:
7138 case BuiltinType::Char32:
7139 case BuiltinType::ObjCId:
7140 case BuiltinType::ObjCClass:
7141 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007142#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7143 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007144#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007145 case BuiltinType::OCLSampler:
7146 case BuiltinType::OCLEvent:
7147 case BuiltinType::OCLClkEvent:
7148 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007149 case BuiltinType::OCLReserveID:
7150 case BuiltinType::Dependent:
7151 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7152 };
7153
7154 case Type::Enum:
7155 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7156 break;
7157
7158 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007159 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007160 break;
7161
7162 case Type::MemberPointer:
7163 if (CanTy->isMemberDataPointerType())
7164 return offset_type_class;
7165 else {
7166 // We expect member pointers to be either data or function pointers,
7167 // nothing else.
7168 assert(CanTy->isMemberFunctionPointerType());
7169 return method_type_class;
7170 }
7171
7172 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007173 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007174
7175 case Type::FunctionNoProto:
7176 case Type::FunctionProto:
7177 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7178
7179 case Type::Record:
7180 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7181 switch (RT->getDecl()->getTagKind()) {
7182 case TagTypeKind::TTK_Struct:
7183 case TagTypeKind::TTK_Class:
7184 case TagTypeKind::TTK_Interface:
7185 return record_type_class;
7186
7187 case TagTypeKind::TTK_Enum:
7188 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7189
7190 case TagTypeKind::TTK_Union:
7191 return union_type_class;
7192 }
7193 }
David Blaikie83d382b2011-09-23 05:06:16 +00007194 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007195
7196 case Type::ConstantArray:
7197 case Type::VariableArray:
7198 case Type::IncompleteArray:
7199 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7200
7201 case Type::BlockPointer:
7202 case Type::LValueReference:
7203 case Type::RValueReference:
7204 case Type::Vector:
7205 case Type::ExtVector:
7206 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007207 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007208 case Type::ObjCObject:
7209 case Type::ObjCInterface:
7210 case Type::ObjCObjectPointer:
7211 case Type::Pipe:
7212 case Type::Atomic:
7213 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7214 }
7215
7216 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007217}
7218
Richard Smith5fab0c92011-12-28 19:48:30 +00007219/// EvaluateBuiltinConstantPForLValue - Determine the result of
7220/// __builtin_constant_p when applied to the given lvalue.
7221///
7222/// An lvalue is only "constant" if it is a pointer or reference to the first
7223/// character of a string literal.
7224template<typename LValue>
7225static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007226 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007227 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7228}
7229
7230/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7231/// GCC as we can manage.
7232static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7233 QualType ArgType = Arg->getType();
7234
7235 // __builtin_constant_p always has one operand. The rules which gcc follows
7236 // are not precisely documented, but are as follows:
7237 //
7238 // - If the operand is of integral, floating, complex or enumeration type,
7239 // and can be folded to a known value of that type, it returns 1.
7240 // - If the operand and can be folded to a pointer to the first character
7241 // of a string literal (or such a pointer cast to an integral type), it
7242 // returns 1.
7243 //
7244 // Otherwise, it returns 0.
7245 //
7246 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7247 // its support for this does not currently work.
7248 if (ArgType->isIntegralOrEnumerationType()) {
7249 Expr::EvalResult Result;
7250 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7251 return false;
7252
7253 APValue &V = Result.Val;
7254 if (V.getKind() == APValue::Int)
7255 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007256 if (V.getKind() == APValue::LValue)
7257 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007258 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7259 return Arg->isEvaluatable(Ctx);
7260 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7261 LValue LV;
7262 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007263 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007264 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7265 : EvaluatePointer(Arg, LV, Info)) &&
7266 !Status.HasSideEffects)
7267 return EvaluateBuiltinConstantPForLValue(LV);
7268 }
7269
7270 // Anything else isn't considered to be sufficiently constant.
7271 return false;
7272}
7273
John McCall95007602010-05-10 23:27:23 +00007274/// Retrieves the "underlying object type" of the given expression,
7275/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007276static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007277 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7278 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007279 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007280 } else if (const Expr *E = B.get<const Expr*>()) {
7281 if (isa<CompoundLiteralExpr>(E))
7282 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007283 }
7284
7285 return QualType();
7286}
7287
George Burgess IV3a03fab2015-09-04 21:28:13 +00007288/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007289/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007290/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007291/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7292///
7293/// Always returns an RValue with a pointer representation.
7294static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7295 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7296
7297 auto *NoParens = E->IgnoreParens();
7298 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007299 if (Cast == nullptr)
7300 return NoParens;
7301
7302 // We only conservatively allow a few kinds of casts, because this code is
7303 // inherently a simple solution that seeks to support the common case.
7304 auto CastKind = Cast->getCastKind();
7305 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7306 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007307 return NoParens;
7308
7309 auto *SubExpr = Cast->getSubExpr();
7310 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7311 return NoParens;
7312 return ignorePointerCastsAndParens(SubExpr);
7313}
7314
George Burgess IVa51c4072015-10-16 01:49:01 +00007315/// Checks to see if the given LValue's Designator is at the end of the LValue's
7316/// record layout. e.g.
7317/// struct { struct { int a, b; } fst, snd; } obj;
7318/// obj.fst // no
7319/// obj.snd // yes
7320/// obj.fst.a // no
7321/// obj.fst.b // no
7322/// obj.snd.a // no
7323/// obj.snd.b // yes
7324///
7325/// Please note: this function is specialized for how __builtin_object_size
7326/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007327///
7328/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007329static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7330 assert(!LVal.Designator.Invalid);
7331
George Burgess IV4168d752016-06-27 19:40:41 +00007332 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7333 const RecordDecl *Parent = FD->getParent();
7334 Invalid = Parent->isInvalidDecl();
7335 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007336 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007337 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007338 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7339 };
7340
7341 auto &Base = LVal.getLValueBase();
7342 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7343 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007344 bool Invalid;
7345 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7346 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007347 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007348 for (auto *FD : IFD->chain()) {
7349 bool Invalid;
7350 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7351 return Invalid;
7352 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007353 }
7354 }
7355
George Burgess IVe3763372016-12-22 02:50:20 +00007356 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007357 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007358 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7359 assert(isBaseAnAllocSizeCall(Base) &&
7360 "Unsized array in non-alloc_size call?");
7361 // If this is an alloc_size base, we should ignore the initial array index
George Burgess IVe3763372016-12-22 02:50:20 +00007362 ++I;
7363 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7364 }
7365
7366 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7367 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007368 if (BaseType->isArrayType()) {
7369 // Because __builtin_object_size treats arrays as objects, we can ignore
7370 // the index iff this is the last array in the Designator.
7371 if (I + 1 == E)
7372 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007373 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7374 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007375 if (Index + 1 != CAT->getSize())
7376 return false;
7377 BaseType = CAT->getElementType();
7378 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007379 const auto *CT = BaseType->castAs<ComplexType>();
7380 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007381 if (Index != 1)
7382 return false;
7383 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007384 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007385 bool Invalid;
7386 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7387 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007388 BaseType = FD->getType();
7389 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007390 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007391 return false;
7392 }
7393 }
7394 return true;
7395}
7396
George Burgess IVe3763372016-12-22 02:50:20 +00007397/// Tests to see if the LValue has a user-specified designator (that isn't
7398/// necessarily valid). Note that this always returns 'true' if the LValue has
7399/// an unsized array as its first designator entry, because there's currently no
7400/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007401static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007402 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007403 return false;
7404
George Burgess IVe3763372016-12-22 02:50:20 +00007405 if (!LVal.Designator.Entries.empty())
7406 return LVal.Designator.isMostDerivedAnUnsizedArray();
7407
George Burgess IVa51c4072015-10-16 01:49:01 +00007408 if (!LVal.InvalidBase)
7409 return true;
7410
George Burgess IVe3763372016-12-22 02:50:20 +00007411 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7412 // the LValueBase.
7413 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7414 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007415}
7416
George Burgess IVe3763372016-12-22 02:50:20 +00007417/// Attempts to detect a user writing into a piece of memory that's impossible
7418/// to figure out the size of by just using types.
7419static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7420 const SubobjectDesignator &Designator = LVal.Designator;
7421 // Notes:
7422 // - Users can only write off of the end when we have an invalid base. Invalid
7423 // bases imply we don't know where the memory came from.
7424 // - We used to be a bit more aggressive here; we'd only be conservative if
7425 // the array at the end was flexible, or if it had 0 or 1 elements. This
7426 // broke some common standard library extensions (PR30346), but was
7427 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7428 // with some sort of whitelist. OTOH, it seems that GCC is always
7429 // conservative with the last element in structs (if it's an array), so our
7430 // current behavior is more compatible than a whitelisting approach would
7431 // be.
7432 return LVal.InvalidBase &&
7433 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7434 Designator.MostDerivedIsArrayElement &&
7435 isDesignatorAtObjectEnd(Ctx, LVal);
7436}
7437
7438/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7439/// Fails if the conversion would cause loss of precision.
7440static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7441 CharUnits &Result) {
7442 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7443 if (Int.ugt(CharUnitsMax))
7444 return false;
7445 Result = CharUnits::fromQuantity(Int.getZExtValue());
7446 return true;
7447}
7448
7449/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7450/// determine how many bytes exist from the beginning of the object to either
7451/// the end of the current subobject, or the end of the object itself, depending
7452/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007453///
George Burgess IVe3763372016-12-22 02:50:20 +00007454/// If this returns false, the value of Result is undefined.
7455static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7456 unsigned Type, const LValue &LVal,
7457 CharUnits &EndOffset) {
7458 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007459
George Burgess IV7fb7e362017-01-03 23:35:19 +00007460 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7461 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7462 return false;
7463 return HandleSizeof(Info, ExprLoc, Ty, Result);
7464 };
7465
George Burgess IVe3763372016-12-22 02:50:20 +00007466 // We want to evaluate the size of the entire object. This is a valid fallback
7467 // for when Type=1 and the designator is invalid, because we're asked for an
7468 // upper-bound.
7469 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7470 // Type=3 wants a lower bound, so we can't fall back to this.
7471 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007472 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007473
7474 llvm::APInt APEndOffset;
7475 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7476 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7477 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7478
7479 if (LVal.InvalidBase)
7480 return false;
7481
7482 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007483 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007484 }
7485
George Burgess IVe3763372016-12-22 02:50:20 +00007486 // We want to evaluate the size of a subobject.
7487 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007488
7489 // The following is a moderately common idiom in C:
7490 //
7491 // struct Foo { int a; char c[1]; };
7492 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7493 // strcpy(&F->c[0], Bar);
7494 //
George Burgess IVe3763372016-12-22 02:50:20 +00007495 // In order to not break too much legacy code, we need to support it.
7496 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7497 // If we can resolve this to an alloc_size call, we can hand that back,
7498 // because we know for certain how many bytes there are to write to.
7499 llvm::APInt APEndOffset;
7500 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7501 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7502 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7503
7504 // If we cannot determine the size of the initial allocation, then we can't
7505 // given an accurate upper-bound. However, we are still able to give
7506 // conservative lower-bounds for Type=3.
7507 if (Type == 1)
7508 return false;
7509 }
7510
7511 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007512 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007513 return false;
7514
George Burgess IVe3763372016-12-22 02:50:20 +00007515 // According to the GCC documentation, we want the size of the subobject
7516 // denoted by the pointer. But that's not quite right -- what we actually
7517 // want is the size of the immediately-enclosing array, if there is one.
7518 int64_t ElemsRemaining;
7519 if (Designator.MostDerivedIsArrayElement &&
7520 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7521 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7522 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7523 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7524 } else {
7525 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7526 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007527
George Burgess IVe3763372016-12-22 02:50:20 +00007528 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7529 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007530}
7531
George Burgess IVe3763372016-12-22 02:50:20 +00007532/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7533/// returns true and stores the result in @p Size.
7534///
7535/// If @p WasError is non-null, this will report whether the failure to evaluate
7536/// is to be treated as an Error in IntExprEvaluator.
7537static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7538 EvalInfo &Info, uint64_t &Size) {
7539 // Determine the denoted object.
7540 LValue LVal;
7541 {
7542 // The operand of __builtin_object_size is never evaluated for side-effects.
7543 // If there are any, but we can determine the pointed-to object anyway, then
7544 // ignore the side-effects.
7545 SpeculativeEvaluationRAII SpeculativeEval(Info);
7546 FoldOffsetRAII Fold(Info);
7547
7548 if (E->isGLValue()) {
7549 // It's possible for us to be given GLValues if we're called via
7550 // Expr::tryEvaluateObjectSize.
7551 APValue RVal;
7552 if (!EvaluateAsRValue(Info, E, RVal))
7553 return false;
7554 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007555 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7556 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007557 return false;
7558 }
7559
7560 // If we point to before the start of the object, there are no accessible
7561 // bytes.
7562 if (LVal.getLValueOffset().isNegative()) {
7563 Size = 0;
7564 return true;
7565 }
7566
7567 CharUnits EndOffset;
7568 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7569 return false;
7570
7571 // If we've fallen outside of the end offset, just pretend there's nothing to
7572 // write to/read from.
7573 if (EndOffset <= LVal.getLValueOffset())
7574 Size = 0;
7575 else
7576 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7577 return true;
John McCall95007602010-05-10 23:27:23 +00007578}
7579
Peter Collingbournee9200682011-05-13 03:29:01 +00007580bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007581 if (unsigned BuiltinOp = E->getBuiltinCallee())
7582 return VisitBuiltinCallExpr(E, BuiltinOp);
7583
7584 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7585}
7586
7587bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7588 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007589 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007590 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007591 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007592
7593 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007594 // The type was checked when we built the expression.
7595 unsigned Type =
7596 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7597 assert(Type <= 3 && "unexpected type");
7598
George Burgess IVe3763372016-12-22 02:50:20 +00007599 uint64_t Size;
7600 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7601 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007602
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007603 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007604 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007605
Richard Smith01ade172012-05-23 04:13:20 +00007606 // Expression had no side effects, but we couldn't statically determine the
7607 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007608 switch (Info.EvalMode) {
7609 case EvalInfo::EM_ConstantExpression:
7610 case EvalInfo::EM_PotentialConstantExpression:
7611 case EvalInfo::EM_ConstantFold:
7612 case EvalInfo::EM_EvaluateForOverflow:
7613 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007614 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007615 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007616 return Error(E);
7617 case EvalInfo::EM_ConstantExpressionUnevaluated:
7618 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007619 // Reduce it to a constant now.
7620 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007621 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007622
7623 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007624 }
7625
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007626 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007627 case Builtin::BI__builtin_bswap32:
7628 case Builtin::BI__builtin_bswap64: {
7629 APSInt Val;
7630 if (!EvaluateInteger(E->getArg(0), Val, Info))
7631 return false;
7632
7633 return Success(Val.byteSwap(), E);
7634 }
7635
Richard Smith8889a3d2013-06-13 06:26:32 +00007636 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007637 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007638
7639 // FIXME: BI__builtin_clrsb
7640 // FIXME: BI__builtin_clrsbl
7641 // FIXME: BI__builtin_clrsbll
7642
Richard Smith80b3c8e2013-06-13 05:04:16 +00007643 case Builtin::BI__builtin_clz:
7644 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007645 case Builtin::BI__builtin_clzll:
7646 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007647 APSInt Val;
7648 if (!EvaluateInteger(E->getArg(0), Val, Info))
7649 return false;
7650 if (!Val)
7651 return Error(E);
7652
7653 return Success(Val.countLeadingZeros(), E);
7654 }
7655
Richard Smith8889a3d2013-06-13 06:26:32 +00007656 case Builtin::BI__builtin_constant_p:
7657 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7658
Richard Smith80b3c8e2013-06-13 05:04:16 +00007659 case Builtin::BI__builtin_ctz:
7660 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007661 case Builtin::BI__builtin_ctzll:
7662 case Builtin::BI__builtin_ctzs: {
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.countTrailingZeros(), E);
7670 }
7671
Richard Smith8889a3d2013-06-13 06:26:32 +00007672 case Builtin::BI__builtin_eh_return_data_regno: {
7673 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7674 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7675 return Success(Operand, E);
7676 }
7677
7678 case Builtin::BI__builtin_expect:
7679 return Visit(E->getArg(0));
7680
7681 case Builtin::BI__builtin_ffs:
7682 case Builtin::BI__builtin_ffsl:
7683 case Builtin::BI__builtin_ffsll: {
7684 APSInt Val;
7685 if (!EvaluateInteger(E->getArg(0), Val, Info))
7686 return false;
7687
7688 unsigned N = Val.countTrailingZeros();
7689 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7690 }
7691
7692 case Builtin::BI__builtin_fpclassify: {
7693 APFloat Val(0.0);
7694 if (!EvaluateFloat(E->getArg(5), Val, Info))
7695 return false;
7696 unsigned Arg;
7697 switch (Val.getCategory()) {
7698 case APFloat::fcNaN: Arg = 0; break;
7699 case APFloat::fcInfinity: Arg = 1; break;
7700 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7701 case APFloat::fcZero: Arg = 4; break;
7702 }
7703 return Visit(E->getArg(Arg));
7704 }
7705
7706 case Builtin::BI__builtin_isinf_sign: {
7707 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007708 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007709 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7710 }
7711
Richard Smithea3019d2013-10-15 19:07:14 +00007712 case Builtin::BI__builtin_isinf: {
7713 APFloat Val(0.0);
7714 return EvaluateFloat(E->getArg(0), Val, Info) &&
7715 Success(Val.isInfinity() ? 1 : 0, E);
7716 }
7717
7718 case Builtin::BI__builtin_isfinite: {
7719 APFloat Val(0.0);
7720 return EvaluateFloat(E->getArg(0), Val, Info) &&
7721 Success(Val.isFinite() ? 1 : 0, E);
7722 }
7723
7724 case Builtin::BI__builtin_isnan: {
7725 APFloat Val(0.0);
7726 return EvaluateFloat(E->getArg(0), Val, Info) &&
7727 Success(Val.isNaN() ? 1 : 0, E);
7728 }
7729
7730 case Builtin::BI__builtin_isnormal: {
7731 APFloat Val(0.0);
7732 return EvaluateFloat(E->getArg(0), Val, Info) &&
7733 Success(Val.isNormal() ? 1 : 0, E);
7734 }
7735
Richard Smith8889a3d2013-06-13 06:26:32 +00007736 case Builtin::BI__builtin_parity:
7737 case Builtin::BI__builtin_parityl:
7738 case Builtin::BI__builtin_parityll: {
7739 APSInt Val;
7740 if (!EvaluateInteger(E->getArg(0), Val, Info))
7741 return false;
7742
7743 return Success(Val.countPopulation() % 2, E);
7744 }
7745
Richard Smith80b3c8e2013-06-13 05:04:16 +00007746 case Builtin::BI__builtin_popcount:
7747 case Builtin::BI__builtin_popcountl:
7748 case Builtin::BI__builtin_popcountll: {
7749 APSInt Val;
7750 if (!EvaluateInteger(E->getArg(0), Val, Info))
7751 return false;
7752
7753 return Success(Val.countPopulation(), E);
7754 }
7755
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007756 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007757 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007758 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007759 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007760 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007761 << /*isConstexpr*/0 << /*isConstructor*/0
7762 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007763 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007764 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007765 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007766 case Builtin::BI__builtin_strlen:
7767 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007768 // As an extension, we support __builtin_strlen() as a constant expression,
7769 // and support folding strlen() to a constant.
7770 LValue String;
7771 if (!EvaluatePointer(E->getArg(0), String, Info))
7772 return false;
7773
Richard Smith8110c9d2016-11-29 19:45:17 +00007774 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7775
Richard Smithe6c19f22013-11-15 02:10:04 +00007776 // Fast path: if it's a string literal, search the string value.
7777 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7778 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007779 // The string literal may have embedded null characters. Find the first
7780 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007781 StringRef Str = S->getBytes();
7782 int64_t Off = String.Offset.getQuantity();
7783 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007784 S->getCharByteWidth() == 1 &&
7785 // FIXME: Add fast-path for wchar_t too.
7786 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007787 Str = Str.substr(Off);
7788
7789 StringRef::size_type Pos = Str.find(0);
7790 if (Pos != StringRef::npos)
7791 Str = Str.substr(0, Pos);
7792
7793 return Success(Str.size(), E);
7794 }
7795
7796 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007797 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007798
7799 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007800 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7801 APValue Char;
7802 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7803 !Char.isInt())
7804 return false;
7805 if (!Char.getInt())
7806 return Success(Strlen, E);
7807 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7808 return false;
7809 }
7810 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007811
Richard Smithe151bab2016-11-11 23:43:35 +00007812 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007813 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007814 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007815 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007816 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007817 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007818 // A call to strlen is not a constant expression.
7819 if (Info.getLangOpts().CPlusPlus11)
7820 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7821 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007822 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007823 else
7824 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7825 // Fall through.
7826 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007827 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007828 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007829 case Builtin::BI__builtin_wcsncmp:
7830 case Builtin::BI__builtin_memcmp:
7831 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007832 LValue String1, String2;
7833 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7834 !EvaluatePointer(E->getArg(1), String2, Info))
7835 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007836
7837 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7838
Richard Smithe151bab2016-11-11 23:43:35 +00007839 uint64_t MaxLength = uint64_t(-1);
7840 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007841 BuiltinOp != Builtin::BIwcscmp &&
7842 BuiltinOp != Builtin::BI__builtin_strcmp &&
7843 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007844 APSInt N;
7845 if (!EvaluateInteger(E->getArg(2), N, Info))
7846 return false;
7847 MaxLength = N.getExtValue();
7848 }
7849 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007850 BuiltinOp != Builtin::BIwmemcmp &&
7851 BuiltinOp != Builtin::BI__builtin_memcmp &&
7852 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007853 for (; MaxLength; --MaxLength) {
7854 APValue Char1, Char2;
7855 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7856 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7857 !Char1.isInt() || !Char2.isInt())
7858 return false;
7859 if (Char1.getInt() != Char2.getInt())
7860 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7861 if (StopAtNull && !Char1.getInt())
7862 return Success(0, E);
7863 assert(!(StopAtNull && !Char2.getInt()));
7864 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7865 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7866 return false;
7867 }
7868 // We hit the strncmp / memcmp limit.
7869 return Success(0, E);
7870 }
7871
Richard Smith01ba47d2012-04-13 00:45:38 +00007872 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007873 case Builtin::BI__atomic_is_lock_free:
7874 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007875 APSInt SizeVal;
7876 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7877 return false;
7878
7879 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7880 // of two less than the maximum inline atomic width, we know it is
7881 // lock-free. If the size isn't a power of two, or greater than the
7882 // maximum alignment where we promote atomics, we know it is not lock-free
7883 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7884 // the answer can only be determined at runtime; for example, 16-byte
7885 // atomics have lock-free implementations on some, but not all,
7886 // x86-64 processors.
7887
7888 // Check power-of-two.
7889 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007890 if (Size.isPowerOfTwo()) {
7891 // Check against inlining width.
7892 unsigned InlineWidthBits =
7893 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7894 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7895 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7896 Size == CharUnits::One() ||
7897 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7898 Expr::NPC_NeverValueDependent))
7899 // OK, we will inline appropriately-aligned operations of this size,
7900 // and _Atomic(T) is appropriately-aligned.
7901 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007902
Richard Smith01ba47d2012-04-13 00:45:38 +00007903 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7904 castAs<PointerType>()->getPointeeType();
7905 if (!PointeeType->isIncompleteType() &&
7906 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7907 // OK, we will inline operations on this object.
7908 return Success(1, E);
7909 }
7910 }
7911 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007912
Richard Smith01ba47d2012-04-13 00:45:38 +00007913 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7914 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007915 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007916 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007917}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007918
Richard Smith8b3497e2011-10-31 01:37:14 +00007919static bool HasSameBase(const LValue &A, const LValue &B) {
7920 if (!A.getLValueBase())
7921 return !B.getLValueBase();
7922 if (!B.getLValueBase())
7923 return false;
7924
Richard Smithce40ad62011-11-12 22:28:03 +00007925 if (A.getLValueBase().getOpaqueValue() !=
7926 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007927 const Decl *ADecl = GetLValueBaseDecl(A);
7928 if (!ADecl)
7929 return false;
7930 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007931 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007932 return false;
7933 }
7934
7935 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007936 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007937}
7938
Richard Smithd20f1e62014-10-21 23:01:04 +00007939/// \brief Determine whether this is a pointer past the end of the complete
7940/// object referred to by the lvalue.
7941static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7942 const LValue &LV) {
7943 // A null pointer can be viewed as being "past the end" but we don't
7944 // choose to look at it that way here.
7945 if (!LV.getLValueBase())
7946 return false;
7947
7948 // If the designator is valid and refers to a subobject, we're not pointing
7949 // past the end.
7950 if (!LV.getLValueDesignator().Invalid &&
7951 !LV.getLValueDesignator().isOnePastTheEnd())
7952 return false;
7953
David Majnemerc378ca52015-08-29 08:32:55 +00007954 // A pointer to an incomplete type might be past-the-end if the type's size is
7955 // zero. We cannot tell because the type is incomplete.
7956 QualType Ty = getType(LV.getLValueBase());
7957 if (Ty->isIncompleteType())
7958 return true;
7959
Richard Smithd20f1e62014-10-21 23:01:04 +00007960 // We're a past-the-end pointer if we point to the byte after the object,
7961 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007962 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007963 return LV.getLValueOffset() == Size;
7964}
7965
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007966namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007967
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007968/// \brief Data recursive integer evaluator of certain binary operators.
7969///
7970/// We use a data recursive algorithm for binary operators so that we are able
7971/// to handle extreme cases of chained binary operators without causing stack
7972/// overflow.
7973class DataRecursiveIntBinOpEvaluator {
7974 struct EvalResult {
7975 APValue Val;
7976 bool Failed;
7977
7978 EvalResult() : Failed(false) { }
7979
7980 void swap(EvalResult &RHS) {
7981 Val.swap(RHS.Val);
7982 Failed = RHS.Failed;
7983 RHS.Failed = false;
7984 }
7985 };
7986
7987 struct Job {
7988 const Expr *E;
7989 EvalResult LHSResult; // meaningful only for binary operator expression.
7990 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007991
David Blaikie73726062015-08-12 23:09:24 +00007992 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007993 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007994
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007995 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007996 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007997 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007998
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007999 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008000 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008001 };
8002
8003 SmallVector<Job, 16> Queue;
8004
8005 IntExprEvaluator &IntEval;
8006 EvalInfo &Info;
8007 APValue &FinalResult;
8008
8009public:
8010 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8011 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8012
8013 /// \brief True if \param E is a binary operator that we are going to handle
8014 /// data recursively.
8015 /// We handle binary operators that are comma, logical, or that have operands
8016 /// with integral or enumeration type.
8017 static bool shouldEnqueue(const BinaryOperator *E) {
8018 return E->getOpcode() == BO_Comma ||
8019 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00008020 (E->isRValue() &&
8021 E->getType()->isIntegralOrEnumerationType() &&
8022 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008023 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008024 }
8025
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008026 bool Traverse(const BinaryOperator *E) {
8027 enqueue(E);
8028 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008029 while (!Queue.empty())
8030 process(PrevResult);
8031
8032 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008033
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008034 FinalResult.swap(PrevResult.Val);
8035 return true;
8036 }
8037
8038private:
8039 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8040 return IntEval.Success(Value, E, Result);
8041 }
8042 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8043 return IntEval.Success(Value, E, Result);
8044 }
8045 bool Error(const Expr *E) {
8046 return IntEval.Error(E);
8047 }
8048 bool Error(const Expr *E, diag::kind D) {
8049 return IntEval.Error(E, D);
8050 }
8051
8052 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8053 return Info.CCEDiag(E, D);
8054 }
8055
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008056 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8057 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008058 bool &SuppressRHSDiags);
8059
8060 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8061 const BinaryOperator *E, APValue &Result);
8062
8063 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8064 Result.Failed = !Evaluate(Result.Val, Info, E);
8065 if (Result.Failed)
8066 Result.Val = APValue();
8067 }
8068
Richard Trieuba4d0872012-03-21 23:30:30 +00008069 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008070
8071 void enqueue(const Expr *E) {
8072 E = E->IgnoreParens();
8073 Queue.resize(Queue.size()+1);
8074 Queue.back().E = E;
8075 Queue.back().Kind = Job::AnyExprKind;
8076 }
8077};
8078
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008079}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008080
8081bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008082 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008083 bool &SuppressRHSDiags) {
8084 if (E->getOpcode() == BO_Comma) {
8085 // Ignore LHS but note if we could not evaluate it.
8086 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008087 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008088 return true;
8089 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008090
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008091 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008092 bool LHSAsBool;
8093 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008094 // We were able to evaluate the LHS, see if we can get away with not
8095 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008096 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8097 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008098 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008099 }
8100 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008101 LHSResult.Failed = true;
8102
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008103 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008104 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008105 if (!Info.noteSideEffect())
8106 return false;
8107
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008108 // We can't evaluate the LHS; however, sometimes the result
8109 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8110 // Don't ignore RHS and suppress diagnostics from this arm.
8111 SuppressRHSDiags = true;
8112 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008113
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008114 return true;
8115 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008116
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008117 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8118 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008119
George Burgess IVa145e252016-05-25 22:38:36 +00008120 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008121 return false; // Ignore RHS;
8122
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008123 return true;
8124}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008125
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008126static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8127 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008128 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8129 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8130 // offsets.
8131 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8132 CharUnits &Offset = LVal.getLValueOffset();
8133 uint64_t Offset64 = Offset.getQuantity();
8134 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8135 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8136 : Offset64 + Index64);
8137}
8138
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008139bool DataRecursiveIntBinOpEvaluator::
8140 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8141 const BinaryOperator *E, APValue &Result) {
8142 if (E->getOpcode() == BO_Comma) {
8143 if (RHSResult.Failed)
8144 return false;
8145 Result = RHSResult.Val;
8146 return true;
8147 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008148
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008149 if (E->isLogicalOp()) {
8150 bool lhsResult, rhsResult;
8151 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8152 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Daniel Jasperffdee092017-05-02 19:21:42 +00008153
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008154 if (LHSIsOK) {
8155 if (RHSIsOK) {
8156 if (E->getOpcode() == BO_LOr)
8157 return Success(lhsResult || rhsResult, E, Result);
8158 else
8159 return Success(lhsResult && rhsResult, E, Result);
8160 }
8161 } else {
8162 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008163 // We can't evaluate the LHS; however, sometimes the result
8164 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8165 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008166 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008167 }
8168 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008169
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008170 return false;
8171 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008172
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008173 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8174 E->getRHS()->getType()->isIntegralOrEnumerationType());
Daniel Jasperffdee092017-05-02 19:21:42 +00008175
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008176 if (LHSResult.Failed || RHSResult.Failed)
8177 return false;
Daniel Jasperffdee092017-05-02 19:21:42 +00008178
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008179 const APValue &LHSVal = LHSResult.Val;
8180 const APValue &RHSVal = RHSResult.Val;
Daniel Jasperffdee092017-05-02 19:21:42 +00008181
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008182 // Handle cases like (unsigned long)&a + 4.
8183 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8184 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008185 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008186 return true;
8187 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008188
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008189 // Handle cases like 4 + (unsigned long)&a
8190 if (E->getOpcode() == BO_Add &&
8191 RHSVal.isLValue() && LHSVal.isInt()) {
8192 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008193 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008194 return true;
8195 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008196
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008197 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8198 // Handle (intptr_t)&&A - (intptr_t)&&B.
8199 if (!LHSVal.getLValueOffset().isZero() ||
8200 !RHSVal.getLValueOffset().isZero())
8201 return false;
8202 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8203 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8204 if (!LHSExpr || !RHSExpr)
8205 return false;
8206 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8207 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8208 if (!LHSAddrExpr || !RHSAddrExpr)
8209 return false;
8210 // Make sure both labels come from the same function.
8211 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8212 RHSAddrExpr->getLabel()->getDeclContext())
8213 return false;
8214 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8215 return true;
8216 }
Richard Smith43e77732013-05-07 04:50:00 +00008217
8218 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008219 if (!LHSVal.isInt() || !RHSVal.isInt())
8220 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008221
8222 // Set up the width and signedness manually, in case it can't be deduced
8223 // from the operation we're performing.
8224 // FIXME: Don't do this in the cases where we can deduce it.
8225 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8226 E->getType()->isUnsignedIntegerOrEnumerationType());
8227 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8228 RHSVal.getInt(), Value))
8229 return false;
8230 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008231}
8232
Richard Trieuba4d0872012-03-21 23:30:30 +00008233void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008234 Job &job = Queue.back();
Daniel Jasperffdee092017-05-02 19:21:42 +00008235
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008236 switch (job.Kind) {
8237 case Job::AnyExprKind: {
8238 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8239 if (shouldEnqueue(Bop)) {
8240 job.Kind = Job::BinOpKind;
8241 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008242 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008243 }
8244 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008245
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008246 EvaluateExpr(job.E, Result);
8247 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008248 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008249 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008250
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008251 case Job::BinOpKind: {
8252 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008253 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008254 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008255 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008256 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008257 }
8258 if (SuppressRHSDiags)
8259 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008260 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008261 job.Kind = Job::BinOpVisitedLHSKind;
8262 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008263 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008264 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008265
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008266 case Job::BinOpVisitedLHSKind: {
8267 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8268 EvalResult RHS;
8269 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008270 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
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 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008275
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008276 llvm_unreachable("Invalid Job::Kind!");
8277}
8278
George Burgess IV8c892b52016-05-25 22:31:54 +00008279namespace {
8280/// Used when we determine that we should fail, but can keep evaluating prior to
8281/// noting that we had a failure.
8282class DelayedNoteFailureRAII {
8283 EvalInfo &Info;
8284 bool NoteFailure;
8285
8286public:
8287 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8288 : Info(Info), NoteFailure(NoteFailure) {}
8289 ~DelayedNoteFailureRAII() {
8290 if (NoteFailure) {
8291 bool ContinueAfterFailure = Info.noteFailure();
8292 (void)ContinueAfterFailure;
8293 assert(ContinueAfterFailure &&
8294 "Shouldn't have kept evaluating on failure.");
8295 }
8296 }
8297};
8298}
8299
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008300bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008301 // We don't call noteFailure immediately because the assignment happens after
8302 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008303 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008304 return Error(E);
8305
George Burgess IV8c892b52016-05-25 22:31:54 +00008306 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008307 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8308 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008309
Anders Carlssonacc79812008-11-16 07:17:21 +00008310 QualType LHSTy = E->getLHS()->getType();
8311 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008312
Chandler Carruthb29a7432014-10-11 11:03:30 +00008313 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008314 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008315 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008316 if (E->isAssignmentOp()) {
8317 LValue LV;
8318 EvaluateLValue(E->getLHS(), LV, Info);
8319 LHSOK = false;
8320 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008321 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8322 if (LHSOK) {
8323 LHS.makeComplexFloat();
8324 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8325 }
8326 } else {
8327 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8328 }
George Burgess IVa145e252016-05-25 22:38:36 +00008329 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008330 return false;
8331
Chandler Carruthb29a7432014-10-11 11:03:30 +00008332 if (E->getRHS()->getType()->isRealFloatingType()) {
8333 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8334 return false;
8335 RHS.makeComplexFloat();
8336 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8337 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008338 return false;
8339
8340 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008341 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008342 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008343 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008344 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8345
John McCalle3027922010-08-25 11:45:40 +00008346 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008347 return Success((CR_r == APFloat::cmpEqual &&
8348 CR_i == APFloat::cmpEqual), E);
8349 else {
John McCalle3027922010-08-25 11:45:40 +00008350 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008351 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008352 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008353 CR_r == APFloat::cmpLessThan ||
8354 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008355 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008356 CR_i == APFloat::cmpLessThan ||
8357 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008358 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008359 } else {
John McCalle3027922010-08-25 11:45:40 +00008360 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008361 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8362 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8363 else {
John McCalle3027922010-08-25 11:45:40 +00008364 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008365 "Invalid compex comparison.");
8366 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8367 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8368 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008369 }
8370 }
Mike Stump11289f42009-09-09 15:08:12 +00008371
Anders Carlssonacc79812008-11-16 07:17:21 +00008372 if (LHSTy->isRealFloatingType() &&
8373 RHSTy->isRealFloatingType()) {
8374 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008375
Richard Smith253c2a32012-01-27 01:14:48 +00008376 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008377 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008378 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008379
Richard Smith253c2a32012-01-27 01:14:48 +00008380 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008381 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008382
Anders Carlssonacc79812008-11-16 07:17:21 +00008383 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008384
Anders Carlssonacc79812008-11-16 07:17:21 +00008385 switch (E->getOpcode()) {
8386 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008387 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008388 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008389 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008390 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008391 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008392 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008393 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008394 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008395 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008396 E);
John McCalle3027922010-08-25 11:45:40 +00008397 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008398 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008399 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008400 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008401 || CR == APFloat::cmpLessThan
8402 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008403 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008404 }
Mike Stump11289f42009-09-09 15:08:12 +00008405
Eli Friedmana38da572009-04-28 19:17:36 +00008406 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008407 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008408 LValue LHSValue, RHSValue;
8409
8410 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008411 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008412 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008413
Richard Smith253c2a32012-01-27 01:14:48 +00008414 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008415 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008416
Richard Smith8b3497e2011-10-31 01:37:14 +00008417 // Reject differing bases from the normal codepath; we special-case
8418 // comparisons to null.
8419 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008420 if (E->getOpcode() == BO_Sub) {
8421 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008422 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008423 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008424 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008425 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008426 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008427 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008428 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8429 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8430 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008431 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008432 // Make sure both labels come from the same function.
8433 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8434 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008435 return Error(E);
8436 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008437 }
Richard Smith83c68212011-10-31 05:11:32 +00008438 // Inequalities and subtractions between unrelated pointers have
8439 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008440 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008441 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008442 // A constant address may compare equal to the address of a symbol.
8443 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008444 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008445 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8446 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008447 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008448 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008449 // distinct addresses. In clang, the result of such a comparison is
8450 // unspecified, so it is not a constant expression. However, we do know
8451 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008452 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8453 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008454 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008455 // We can't tell whether weak symbols will end up pointing to the same
8456 // object.
8457 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008458 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008459 // We can't compare the address of the start of one object with the
8460 // past-the-end address of another object, per C++ DR1652.
8461 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8462 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8463 (RHSValue.Base && RHSValue.Offset.isZero() &&
8464 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8465 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008466 // We can't tell whether an object is at the same address as another
8467 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008468 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8469 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008470 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008471 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008472 // (Note that clang defaults to -fmerge-all-constants, which can
8473 // lead to inconsistent results for comparisons involving the address
8474 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008475 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008476 }
Eli Friedman64004332009-03-23 04:38:34 +00008477
Richard Smith1b470412012-02-01 08:10:20 +00008478 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8479 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8480
Richard Smith84f6dcf2012-02-02 01:16:57 +00008481 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8482 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8483
John McCalle3027922010-08-25 11:45:40 +00008484 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008485 // C++11 [expr.add]p6:
8486 // Unless both pointers point to elements of the same array object, or
8487 // one past the last element of the array object, the behavior is
8488 // undefined.
8489 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8490 !AreElementsOfSameArray(getType(LHSValue.Base),
8491 LHSDesignator, RHSDesignator))
8492 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8493
Chris Lattner882bdf22010-04-20 17:13:14 +00008494 QualType Type = E->getLHS()->getType();
8495 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008496
Richard Smithd62306a2011-11-10 06:34:14 +00008497 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008498 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008499 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008500
Richard Smith84c6b3d2013-09-10 21:34:14 +00008501 // As an extension, a type may have zero size (empty struct or union in
8502 // C, array of zero length). Pointer subtraction in such cases has
8503 // undefined behavior, so is not constant.
8504 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008505 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008506 << ElementType;
8507 return false;
8508 }
8509
Richard Smith1b470412012-02-01 08:10:20 +00008510 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8511 // and produce incorrect results when it overflows. Such behavior
8512 // appears to be non-conforming, but is common, so perhaps we should
8513 // assume the standard intended for such cases to be undefined behavior
8514 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008515
Richard Smith1b470412012-02-01 08:10:20 +00008516 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8517 // overflow in the final conversion to ptrdiff_t.
8518 APSInt LHS(
8519 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8520 APSInt RHS(
8521 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8522 APSInt ElemSize(
8523 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8524 APSInt TrueResult = (LHS - RHS) / ElemSize;
8525 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8526
Richard Smith0c6124b2015-12-03 01:36:22 +00008527 if (Result.extend(65) != TrueResult &&
8528 !HandleOverflow(Info, E, TrueResult, E->getType()))
8529 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008530 return Success(Result, E);
8531 }
Richard Smithde21b242012-01-31 06:41:30 +00008532
8533 // C++11 [expr.rel]p3:
8534 // Pointers to void (after pointer conversions) can be compared, with a
8535 // result defined as follows: If both pointers represent the same
8536 // address or are both the null pointer value, the result is true if the
8537 // operator is <= or >= and false otherwise; otherwise the result is
8538 // unspecified.
8539 // We interpret this as applying to pointers to *cv* void.
8540 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008541 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008542 CCEDiag(E, diag::note_constexpr_void_comparison);
8543
Richard Smith84f6dcf2012-02-02 01:16:57 +00008544 // C++11 [expr.rel]p2:
8545 // - If two pointers point to non-static data members of the same object,
8546 // or to subobjects or array elements fo such members, recursively, the
8547 // pointer to the later declared member compares greater provided the
8548 // two members have the same access control and provided their class is
8549 // not a union.
8550 // [...]
8551 // - Otherwise pointer comparisons are unspecified.
8552 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8553 E->isRelationalOp()) {
8554 bool WasArrayIndex;
8555 unsigned Mismatch =
8556 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8557 RHSDesignator, WasArrayIndex);
8558 // At the point where the designators diverge, the comparison has a
8559 // specified value if:
8560 // - we are comparing array indices
8561 // - we are comparing fields of a union, or fields with the same access
8562 // Otherwise, the result is unspecified and thus the comparison is not a
8563 // constant expression.
8564 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8565 Mismatch < RHSDesignator.Entries.size()) {
8566 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8567 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8568 if (!LF && !RF)
8569 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8570 else if (!LF)
8571 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8572 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8573 << RF->getParent() << RF;
8574 else if (!RF)
8575 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8576 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8577 << LF->getParent() << LF;
8578 else if (!LF->getParent()->isUnion() &&
8579 LF->getAccess() != RF->getAccess())
8580 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8581 << LF << LF->getAccess() << RF << RF->getAccess()
8582 << LF->getParent();
8583 }
8584 }
8585
Eli Friedman6c31cb42012-04-16 04:30:08 +00008586 // The comparison here must be unsigned, and performed with the same
8587 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008588 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8589 uint64_t CompareLHS = LHSOffset.getQuantity();
8590 uint64_t CompareRHS = RHSOffset.getQuantity();
8591 assert(PtrSize <= 64 && "Unexpected pointer width");
8592 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8593 CompareLHS &= Mask;
8594 CompareRHS &= Mask;
8595
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008596 // If there is a base and this is a relational operator, we can only
8597 // compare pointers within the object in question; otherwise, the result
8598 // depends on where the object is located in memory.
8599 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8600 QualType BaseTy = getType(LHSValue.Base);
8601 if (BaseTy->isIncompleteType())
8602 return Error(E);
8603 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8604 uint64_t OffsetLimit = Size.getQuantity();
8605 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8606 return Error(E);
8607 }
8608
Richard Smith8b3497e2011-10-31 01:37:14 +00008609 switch (E->getOpcode()) {
8610 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008611 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8612 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8613 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8614 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8615 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8616 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008617 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008618 }
8619 }
Richard Smith7bb00672012-02-01 01:42:44 +00008620
8621 if (LHSTy->isMemberPointerType()) {
8622 assert(E->isEqualityOp() && "unexpected member pointer operation");
8623 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8624
8625 MemberPtr LHSValue, RHSValue;
8626
8627 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008628 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008629 return false;
8630
8631 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8632 return false;
8633
8634 // C++11 [expr.eq]p2:
8635 // If both operands are null, they compare equal. Otherwise if only one is
8636 // null, they compare unequal.
8637 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8638 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8639 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8640 }
8641
8642 // Otherwise if either is a pointer to a virtual member function, the
8643 // result is unspecified.
8644 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8645 if (MD->isVirtual())
8646 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8647 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8648 if (MD->isVirtual())
8649 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8650
8651 // Otherwise they compare equal if and only if they would refer to the
8652 // same member of the same most derived object or the same subobject if
8653 // they were dereferenced with a hypothetical object of the associated
8654 // class type.
8655 bool Equal = LHSValue == RHSValue;
8656 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8657 }
8658
Richard Smithab44d9b2012-02-14 22:35:28 +00008659 if (LHSTy->isNullPtrType()) {
8660 assert(E->isComparisonOp() && "unexpected nullptr operation");
8661 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8662 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8663 // are compared, the result is true of the operator is <=, >= or ==, and
8664 // false otherwise.
8665 BinaryOperator::Opcode Opcode = E->getOpcode();
8666 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8667 }
8668
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008669 assert((!LHSTy->isIntegralOrEnumerationType() ||
8670 !RHSTy->isIntegralOrEnumerationType()) &&
8671 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8672 // We can't continue from here for non-integral types.
8673 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008674}
8675
Peter Collingbournee190dee2011-03-11 19:24:49 +00008676/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8677/// a result as the expression's type.
8678bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8679 const UnaryExprOrTypeTraitExpr *E) {
8680 switch(E->getKind()) {
8681 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008682 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008683 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008684 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008685 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008686 }
Eli Friedman64004332009-03-23 04:38:34 +00008687
Peter Collingbournee190dee2011-03-11 19:24:49 +00008688 case UETT_VecStep: {
8689 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008690
Peter Collingbournee190dee2011-03-11 19:24:49 +00008691 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008692 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008693
Peter Collingbournee190dee2011-03-11 19:24:49 +00008694 // The vec_step built-in functions that take a 3-component
8695 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8696 if (n == 3)
8697 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008698
Peter Collingbournee190dee2011-03-11 19:24:49 +00008699 return Success(n, E);
8700 } else
8701 return Success(1, E);
8702 }
8703
8704 case UETT_SizeOf: {
8705 QualType SrcTy = E->getTypeOfArgument();
8706 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8707 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008708 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8709 SrcTy = Ref->getPointeeType();
8710
Richard Smithd62306a2011-11-10 06:34:14 +00008711 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008712 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008713 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008714 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008715 }
Alexey Bataev00396512015-07-02 03:40:19 +00008716 case UETT_OpenMPRequiredSimdAlign:
8717 assert(E->isArgumentType());
8718 return Success(
8719 Info.Ctx.toCharUnitsFromBits(
8720 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8721 .getQuantity(),
8722 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008723 }
8724
8725 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008726}
8727
Peter Collingbournee9200682011-05-13 03:29:01 +00008728bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008729 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008730 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008731 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008732 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008733 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008734 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008735 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008736 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008737 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008738 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008739 APSInt IdxResult;
8740 if (!EvaluateInteger(Idx, IdxResult, Info))
8741 return false;
8742 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8743 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008744 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008745 CurrentType = AT->getElementType();
8746 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8747 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008748 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008749 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008750
James Y Knight7281c352015-12-29 22:31:18 +00008751 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008752 FieldDecl *MemberDecl = ON.getField();
8753 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008754 if (!RT)
8755 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008756 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008757 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008758 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008759 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008760 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008761 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008762 CurrentType = MemberDecl->getType().getNonReferenceType();
8763 break;
8764 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008765
James Y Knight7281c352015-12-29 22:31:18 +00008766 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008767 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008768
James Y Knight7281c352015-12-29 22:31:18 +00008769 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008770 CXXBaseSpecifier *BaseSpec = ON.getBase();
8771 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008772 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008773
8774 // Find the layout of the class whose base we are looking into.
8775 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008776 if (!RT)
8777 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008778 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008779 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008780 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8781
8782 // Find the base class itself.
8783 CurrentType = BaseSpec->getType();
8784 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8785 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008786 return Error(OOE);
Daniel Jasperffdee092017-05-02 19:21:42 +00008787
Douglas Gregord1702062010-04-29 00:18:15 +00008788 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008789 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008790 break;
8791 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008792 }
8793 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008794 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008795}
8796
Chris Lattnere13042c2008-07-11 19:10:17 +00008797bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008798 switch (E->getOpcode()) {
8799 default:
8800 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8801 // See C99 6.6p3.
8802 return Error(E);
8803 case UO_Extension:
8804 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8805 // If so, we could clear the diagnostic ID.
8806 return Visit(E->getSubExpr());
8807 case UO_Plus:
8808 // The result is just the value.
8809 return Visit(E->getSubExpr());
8810 case UO_Minus: {
8811 if (!Visit(E->getSubExpr()))
8812 return false;
8813 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008814 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008815 if (Value.isSigned() && Value.isMinSignedValue() &&
8816 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8817 E->getType()))
8818 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008819 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008820 }
8821 case UO_Not: {
8822 if (!Visit(E->getSubExpr()))
8823 return false;
8824 if (!Result.isInt()) return Error(E);
8825 return Success(~Result.getInt(), E);
8826 }
8827 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008828 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008829 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008830 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008831 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008832 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008833 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008834}
Mike Stump11289f42009-09-09 15:08:12 +00008835
Chris Lattner477c4be2008-07-12 01:15:53 +00008836/// HandleCast - This is used to evaluate implicit or explicit casts where the
8837/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008838bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8839 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008840 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008841 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008842
Eli Friedmanc757de22011-03-25 00:43:55 +00008843 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008844 case CK_BaseToDerived:
8845 case CK_DerivedToBase:
8846 case CK_UncheckedDerivedToBase:
8847 case CK_Dynamic:
8848 case CK_ToUnion:
8849 case CK_ArrayToPointerDecay:
8850 case CK_FunctionToPointerDecay:
8851 case CK_NullToPointer:
8852 case CK_NullToMemberPointer:
8853 case CK_BaseToDerivedMemberPointer:
8854 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008855 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008856 case CK_ConstructorConversion:
8857 case CK_IntegralToPointer:
8858 case CK_ToVoid:
8859 case CK_VectorSplat:
8860 case CK_IntegralToFloating:
8861 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008862 case CK_CPointerToObjCPointerCast:
8863 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008864 case CK_AnyPointerToBlockPointerCast:
8865 case CK_ObjCObjectLValueCast:
8866 case CK_FloatingRealToComplex:
8867 case CK_FloatingComplexToReal:
8868 case CK_FloatingComplexCast:
8869 case CK_FloatingComplexToIntegralComplex:
8870 case CK_IntegralRealToComplex:
8871 case CK_IntegralComplexCast:
8872 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008873 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008874 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008875 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008876 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008877 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008878 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008879 llvm_unreachable("invalid cast kind for integral value");
8880
Eli Friedman9faf2f92011-03-25 19:07:11 +00008881 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008882 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008883 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008884 case CK_ARCProduceObject:
8885 case CK_ARCConsumeObject:
8886 case CK_ARCReclaimReturnedObject:
8887 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008888 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008889 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008890
Richard Smith4ef685b2012-01-17 21:17:26 +00008891 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008892 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008893 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008894 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008895 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008896
8897 case CK_MemberPointerToBoolean:
8898 case CK_PointerToBoolean:
8899 case CK_IntegralToBoolean:
8900 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008901 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008902 case CK_FloatingComplexToBoolean:
8903 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008904 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008905 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008906 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008907 uint64_t IntResult = BoolResult;
8908 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8909 IntResult = (uint64_t)-1;
8910 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008911 }
8912
Eli Friedmanc757de22011-03-25 00:43:55 +00008913 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008914 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008915 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008916
Eli Friedman742421e2009-02-20 01:15:07 +00008917 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008918 // Allow casts of address-of-label differences if they are no-ops
8919 // or narrowing. (The narrowing case isn't actually guaranteed to
8920 // be constant-evaluatable except in some narrow cases which are hard
8921 // to detect here. We let it through on the assumption the user knows
8922 // what they are doing.)
8923 if (Result.isAddrLabelDiff())
8924 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008925 // Only allow casts of lvalues if they are lossless.
8926 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8927 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008928
Richard Smith911e1422012-01-30 22:27:01 +00008929 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8930 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008931 }
Mike Stump11289f42009-09-09 15:08:12 +00008932
Eli Friedmanc757de22011-03-25 00:43:55 +00008933 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008934 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8935
John McCall45d55e42010-05-07 21:00:08 +00008936 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008937 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008938 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008939
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008940 if (LV.getLValueBase()) {
8941 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008942 // FIXME: Allow a larger integer size than the pointer size, and allow
8943 // narrowing back down to pointer width in subsequent integral casts.
8944 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008945 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008946 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008947
Richard Smithcf74da72011-11-16 07:18:12 +00008948 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008949 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008950 return true;
8951 }
8952
Yaxun Liu402804b2016-12-15 08:09:08 +00008953 uint64_t V;
8954 if (LV.isNullPointer())
8955 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8956 else
8957 V = LV.getLValueOffset().getQuantity();
8958
8959 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008960 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008961 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008962
Eli Friedmanc757de22011-03-25 00:43:55 +00008963 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008964 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008965 if (!EvaluateComplex(SubExpr, C, Info))
8966 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008967 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008968 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008969
Eli Friedmanc757de22011-03-25 00:43:55 +00008970 case CK_FloatingToIntegral: {
8971 APFloat F(0.0);
8972 if (!EvaluateFloat(SubExpr, F, Info))
8973 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008974
Richard Smith357362d2011-12-13 06:39:58 +00008975 APSInt Value;
8976 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8977 return false;
8978 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008979 }
8980 }
Mike Stump11289f42009-09-09 15:08:12 +00008981
Eli Friedmanc757de22011-03-25 00:43:55 +00008982 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008983}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008984
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008985bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8986 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008987 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008988 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8989 return false;
8990 if (!LV.isComplexInt())
8991 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008992 return Success(LV.getComplexIntReal(), E);
8993 }
8994
8995 return Visit(E->getSubExpr());
8996}
8997
Eli Friedman4e7a2412009-02-27 04:45:43 +00008998bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008999 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009000 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009001 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9002 return false;
9003 if (!LV.isComplexInt())
9004 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009005 return Success(LV.getComplexIntImag(), E);
9006 }
9007
Richard Smith4a678122011-10-24 18:44:57 +00009008 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009009 return Success(0, E);
9010}
9011
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009012bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9013 return Success(E->getPackLength(), E);
9014}
9015
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009016bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9017 return Success(E->getValue(), E);
9018}
9019
Chris Lattner05706e882008-07-11 18:11:29 +00009020//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009021// Float Evaluation
9022//===----------------------------------------------------------------------===//
9023
9024namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009025class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009026 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009027 APFloat &Result;
9028public:
9029 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009030 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009031
Richard Smith2e312c82012-03-03 22:46:17 +00009032 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009033 Result = V.getFloat();
9034 return true;
9035 }
Eli Friedman24c01542008-08-22 00:06:13 +00009036
Richard Smithfddd3842011-12-30 21:15:51 +00009037 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009038 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9039 return true;
9040 }
9041
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009042 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009043
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009044 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009045 bool VisitBinaryOperator(const BinaryOperator *E);
9046 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009047 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009048
John McCallb1fb0d32010-05-07 22:08:54 +00009049 bool VisitUnaryReal(const UnaryOperator *E);
9050 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009051
Richard Smithfddd3842011-12-30 21:15:51 +00009052 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009053};
9054} // end anonymous namespace
9055
9056static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009057 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009058 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009059}
9060
Jay Foad39c79802011-01-12 09:06:06 +00009061static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009062 QualType ResultTy,
9063 const Expr *Arg,
9064 bool SNaN,
9065 llvm::APFloat &Result) {
9066 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9067 if (!S) return false;
9068
9069 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9070
9071 llvm::APInt fill;
9072
9073 // Treat empty strings as if they were zero.
9074 if (S->getString().empty())
9075 fill = llvm::APInt(32, 0);
9076 else if (S->getString().getAsInteger(0, fill))
9077 return false;
9078
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009079 if (Context.getTargetInfo().isNan2008()) {
9080 if (SNaN)
9081 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9082 else
9083 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9084 } else {
9085 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9086 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9087 // a different encoding to what became a standard in 2008, and for pre-
9088 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9089 // sNaN. This is now known as "legacy NaN" encoding.
9090 if (SNaN)
9091 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9092 else
9093 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9094 }
9095
John McCall16291492010-02-28 13:00:19 +00009096 return true;
9097}
9098
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009099bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009100 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009101 default:
9102 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9103
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009104 case Builtin::BI__builtin_huge_val:
9105 case Builtin::BI__builtin_huge_valf:
9106 case Builtin::BI__builtin_huge_vall:
9107 case Builtin::BI__builtin_inf:
9108 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009109 case Builtin::BI__builtin_infl: {
9110 const llvm::fltSemantics &Sem =
9111 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009112 Result = llvm::APFloat::getInf(Sem);
9113 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009114 }
Mike Stump11289f42009-09-09 15:08:12 +00009115
John McCall16291492010-02-28 13:00:19 +00009116 case Builtin::BI__builtin_nans:
9117 case Builtin::BI__builtin_nansf:
9118 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009119 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9120 true, Result))
9121 return Error(E);
9122 return true;
John McCall16291492010-02-28 13:00:19 +00009123
Chris Lattner0b7282e2008-10-06 06:31:58 +00009124 case Builtin::BI__builtin_nan:
9125 case Builtin::BI__builtin_nanf:
9126 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00009127 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009128 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009129 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9130 false, Result))
9131 return Error(E);
9132 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009133
9134 case Builtin::BI__builtin_fabs:
9135 case Builtin::BI__builtin_fabsf:
9136 case Builtin::BI__builtin_fabsl:
9137 if (!EvaluateFloat(E->getArg(0), Result, Info))
9138 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009139
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009140 if (Result.isNegative())
9141 Result.changeSign();
9142 return true;
9143
Richard Smith8889a3d2013-06-13 06:26:32 +00009144 // FIXME: Builtin::BI__builtin_powi
9145 // FIXME: Builtin::BI__builtin_powif
9146 // FIXME: Builtin::BI__builtin_powil
9147
Mike Stump11289f42009-09-09 15:08:12 +00009148 case Builtin::BI__builtin_copysign:
9149 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009150 case Builtin::BI__builtin_copysignl: {
9151 APFloat RHS(0.);
9152 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9153 !EvaluateFloat(E->getArg(1), RHS, Info))
9154 return false;
9155 Result.copySign(RHS);
9156 return true;
9157 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009158 }
9159}
9160
John McCallb1fb0d32010-05-07 22:08:54 +00009161bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009162 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9163 ComplexValue CV;
9164 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9165 return false;
9166 Result = CV.FloatReal;
9167 return true;
9168 }
9169
9170 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009171}
9172
9173bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009174 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9175 ComplexValue CV;
9176 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9177 return false;
9178 Result = CV.FloatImag;
9179 return true;
9180 }
9181
Richard Smith4a678122011-10-24 18:44:57 +00009182 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009183 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9184 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009185 return true;
9186}
9187
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009188bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009189 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009190 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009191 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009192 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009193 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009194 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9195 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009196 Result.changeSign();
9197 return true;
9198 }
9199}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009200
Eli Friedman24c01542008-08-22 00:06:13 +00009201bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009202 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9203 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009204
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009205 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009206 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009207 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009208 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009209 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9210 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009211}
9212
9213bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9214 Result = E->getValue();
9215 return true;
9216}
9217
Peter Collingbournee9200682011-05-13 03:29:01 +00009218bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9219 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009220
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009221 switch (E->getCastKind()) {
9222 default:
Richard Smith11562c52011-10-28 17:51:58 +00009223 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009224
9225 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009226 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009227 return EvaluateInteger(SubExpr, IntResult, Info) &&
9228 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9229 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009230 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009231
9232 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009233 if (!Visit(SubExpr))
9234 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009235 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9236 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009237 }
John McCalld7646252010-11-14 08:17:51 +00009238
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009239 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009240 ComplexValue V;
9241 if (!EvaluateComplex(SubExpr, V, Info))
9242 return false;
9243 Result = V.getComplexFloatReal();
9244 return true;
9245 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009246 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009247}
9248
Eli Friedman24c01542008-08-22 00:06:13 +00009249//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009250// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009251//===----------------------------------------------------------------------===//
9252
9253namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009254class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009255 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009256 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009257
Anders Carlsson537969c2008-11-16 20:27:53 +00009258public:
John McCall93d91dc2010-05-07 17:22:02 +00009259 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009260 : ExprEvaluatorBaseTy(info), Result(Result) {}
9261
Richard Smith2e312c82012-03-03 22:46:17 +00009262 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009263 Result.setFrom(V);
9264 return true;
9265 }
Mike Stump11289f42009-09-09 15:08:12 +00009266
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009267 bool ZeroInitialization(const Expr *E);
9268
Anders Carlsson537969c2008-11-16 20:27:53 +00009269 //===--------------------------------------------------------------------===//
9270 // Visitor Methods
9271 //===--------------------------------------------------------------------===//
9272
Peter Collingbournee9200682011-05-13 03:29:01 +00009273 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009274 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009275 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009276 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009277 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009278};
9279} // end anonymous namespace
9280
John McCall93d91dc2010-05-07 17:22:02 +00009281static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9282 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009283 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009284 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009285}
9286
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009287bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009288 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009289 if (ElemTy->isRealFloatingType()) {
9290 Result.makeComplexFloat();
9291 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9292 Result.FloatReal = Zero;
9293 Result.FloatImag = Zero;
9294 } else {
9295 Result.makeComplexInt();
9296 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9297 Result.IntReal = Zero;
9298 Result.IntImag = Zero;
9299 }
9300 return true;
9301}
9302
Peter Collingbournee9200682011-05-13 03:29:01 +00009303bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9304 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009305
9306 if (SubExpr->getType()->isRealFloatingType()) {
9307 Result.makeComplexFloat();
9308 APFloat &Imag = Result.FloatImag;
9309 if (!EvaluateFloat(SubExpr, Imag, Info))
9310 return false;
9311
9312 Result.FloatReal = APFloat(Imag.getSemantics());
9313 return true;
9314 } else {
9315 assert(SubExpr->getType()->isIntegerType() &&
9316 "Unexpected imaginary literal.");
9317
9318 Result.makeComplexInt();
9319 APSInt &Imag = Result.IntImag;
9320 if (!EvaluateInteger(SubExpr, Imag, Info))
9321 return false;
9322
9323 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9324 return true;
9325 }
9326}
9327
Peter Collingbournee9200682011-05-13 03:29:01 +00009328bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009329
John McCallfcef3cf2010-12-14 17:51:41 +00009330 switch (E->getCastKind()) {
9331 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009332 case CK_BaseToDerived:
9333 case CK_DerivedToBase:
9334 case CK_UncheckedDerivedToBase:
9335 case CK_Dynamic:
9336 case CK_ToUnion:
9337 case CK_ArrayToPointerDecay:
9338 case CK_FunctionToPointerDecay:
9339 case CK_NullToPointer:
9340 case CK_NullToMemberPointer:
9341 case CK_BaseToDerivedMemberPointer:
9342 case CK_DerivedToBaseMemberPointer:
9343 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009344 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009345 case CK_ConstructorConversion:
9346 case CK_IntegralToPointer:
9347 case CK_PointerToIntegral:
9348 case CK_PointerToBoolean:
9349 case CK_ToVoid:
9350 case CK_VectorSplat:
9351 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009352 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009353 case CK_IntegralToBoolean:
9354 case CK_IntegralToFloating:
9355 case CK_FloatingToIntegral:
9356 case CK_FloatingToBoolean:
9357 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009358 case CK_CPointerToObjCPointerCast:
9359 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009360 case CK_AnyPointerToBlockPointerCast:
9361 case CK_ObjCObjectLValueCast:
9362 case CK_FloatingComplexToReal:
9363 case CK_FloatingComplexToBoolean:
9364 case CK_IntegralComplexToReal:
9365 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009366 case CK_ARCProduceObject:
9367 case CK_ARCConsumeObject:
9368 case CK_ARCReclaimReturnedObject:
9369 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009370 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009371 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009372 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009373 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009374 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009375 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009376 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009377 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009378
John McCallfcef3cf2010-12-14 17:51:41 +00009379 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009380 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009381 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009382 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009383
9384 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009385 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009386 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009387 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009388
9389 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009390 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009391 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009392 return false;
9393
John McCallfcef3cf2010-12-14 17:51:41 +00009394 Result.makeComplexFloat();
9395 Result.FloatImag = APFloat(Real.getSemantics());
9396 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009397 }
9398
John McCallfcef3cf2010-12-14 17:51:41 +00009399 case CK_FloatingComplexCast: {
9400 if (!Visit(E->getSubExpr()))
9401 return false;
9402
9403 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9404 QualType From
9405 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9406
Richard Smith357362d2011-12-13 06:39:58 +00009407 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9408 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009409 }
9410
9411 case CK_FloatingComplexToIntegralComplex: {
9412 if (!Visit(E->getSubExpr()))
9413 return false;
9414
9415 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9416 QualType From
9417 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9418 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009419 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9420 To, Result.IntReal) &&
9421 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9422 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009423 }
9424
9425 case CK_IntegralRealToComplex: {
9426 APSInt &Real = Result.IntReal;
9427 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9428 return false;
9429
9430 Result.makeComplexInt();
9431 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9432 return true;
9433 }
9434
9435 case CK_IntegralComplexCast: {
9436 if (!Visit(E->getSubExpr()))
9437 return false;
9438
9439 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9440 QualType From
9441 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9442
Richard Smith911e1422012-01-30 22:27:01 +00009443 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9444 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009445 return true;
9446 }
9447
9448 case CK_IntegralComplexToFloatingComplex: {
9449 if (!Visit(E->getSubExpr()))
9450 return false;
9451
Ted Kremenek28831752012-08-23 20:46:57 +00009452 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009453 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009454 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009455 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009456 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9457 To, Result.FloatReal) &&
9458 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9459 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009460 }
9461 }
9462
9463 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009464}
9465
John McCall93d91dc2010-05-07 17:22:02 +00009466bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009467 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009468 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9469
Chandler Carrutha216cad2014-10-11 00:57:18 +00009470 // Track whether the LHS or RHS is real at the type system level. When this is
9471 // the case we can simplify our evaluation strategy.
9472 bool LHSReal = false, RHSReal = false;
9473
9474 bool LHSOK;
9475 if (E->getLHS()->getType()->isRealFloatingType()) {
9476 LHSReal = true;
9477 APFloat &Real = Result.FloatReal;
9478 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9479 if (LHSOK) {
9480 Result.makeComplexFloat();
9481 Result.FloatImag = APFloat(Real.getSemantics());
9482 }
9483 } else {
9484 LHSOK = Visit(E->getLHS());
9485 }
George Burgess IVa145e252016-05-25 22:38:36 +00009486 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009487 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009488
John McCall93d91dc2010-05-07 17:22:02 +00009489 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009490 if (E->getRHS()->getType()->isRealFloatingType()) {
9491 RHSReal = true;
9492 APFloat &Real = RHS.FloatReal;
9493 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9494 return false;
9495 RHS.makeComplexFloat();
9496 RHS.FloatImag = APFloat(Real.getSemantics());
9497 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009498 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009499
Chandler Carrutha216cad2014-10-11 00:57:18 +00009500 assert(!(LHSReal && RHSReal) &&
9501 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009502 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009503 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009504 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009505 if (Result.isComplexFloat()) {
9506 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9507 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009508 if (LHSReal)
9509 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9510 else if (!RHSReal)
9511 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9512 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009513 } else {
9514 Result.getComplexIntReal() += RHS.getComplexIntReal();
9515 Result.getComplexIntImag() += RHS.getComplexIntImag();
9516 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009517 break;
John McCalle3027922010-08-25 11:45:40 +00009518 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009519 if (Result.isComplexFloat()) {
9520 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9521 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009522 if (LHSReal) {
9523 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9524 Result.getComplexFloatImag().changeSign();
9525 } else if (!RHSReal) {
9526 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9527 APFloat::rmNearestTiesToEven);
9528 }
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_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009535 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009536 // This is an implementation of complex multiplication according to the
9537 // constraints laid out in C11 Annex G. The implemantion uses the
9538 // following naming scheme:
9539 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009540 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009541 APFloat &A = LHS.getComplexFloatReal();
9542 APFloat &B = LHS.getComplexFloatImag();
9543 APFloat &C = RHS.getComplexFloatReal();
9544 APFloat &D = RHS.getComplexFloatImag();
9545 APFloat &ResR = Result.getComplexFloatReal();
9546 APFloat &ResI = Result.getComplexFloatImag();
9547 if (LHSReal) {
9548 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9549 ResR = A * C;
9550 ResI = A * D;
9551 } else if (RHSReal) {
9552 ResR = C * A;
9553 ResI = C * B;
9554 } else {
9555 // In the fully general case, we need to handle NaNs and infinities
9556 // robustly.
9557 APFloat AC = A * C;
9558 APFloat BD = B * D;
9559 APFloat AD = A * D;
9560 APFloat BC = B * C;
9561 ResR = AC - BD;
9562 ResI = AD + BC;
9563 if (ResR.isNaN() && ResI.isNaN()) {
9564 bool Recalc = false;
9565 if (A.isInfinity() || B.isInfinity()) {
9566 A = APFloat::copySign(
9567 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9568 B = APFloat::copySign(
9569 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9570 if (C.isNaN())
9571 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9572 if (D.isNaN())
9573 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9574 Recalc = true;
9575 }
9576 if (C.isInfinity() || D.isInfinity()) {
9577 C = APFloat::copySign(
9578 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9579 D = APFloat::copySign(
9580 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9581 if (A.isNaN())
9582 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9583 if (B.isNaN())
9584 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9585 Recalc = true;
9586 }
9587 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9588 AD.isInfinity() || BC.isInfinity())) {
9589 if (A.isNaN())
9590 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9591 if (B.isNaN())
9592 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9593 if (C.isNaN())
9594 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9595 if (D.isNaN())
9596 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9597 Recalc = true;
9598 }
9599 if (Recalc) {
9600 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9601 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9602 }
9603 }
9604 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009605 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009606 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009607 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009608 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9609 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009610 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009611 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9612 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9613 }
9614 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009615 case BO_Div:
9616 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009617 // This is an implementation of complex division according to the
9618 // constraints laid out in C11 Annex G. The implemantion uses the
9619 // following naming scheme:
9620 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009621 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009622 APFloat &A = LHS.getComplexFloatReal();
9623 APFloat &B = LHS.getComplexFloatImag();
9624 APFloat &C = RHS.getComplexFloatReal();
9625 APFloat &D = RHS.getComplexFloatImag();
9626 APFloat &ResR = Result.getComplexFloatReal();
9627 APFloat &ResI = Result.getComplexFloatImag();
9628 if (RHSReal) {
9629 ResR = A / C;
9630 ResI = B / C;
9631 } else {
9632 if (LHSReal) {
9633 // No real optimizations we can do here, stub out with zero.
9634 B = APFloat::getZero(A.getSemantics());
9635 }
9636 int DenomLogB = 0;
9637 APFloat MaxCD = maxnum(abs(C), abs(D));
9638 if (MaxCD.isFinite()) {
9639 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009640 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9641 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009642 }
9643 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009644 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9645 APFloat::rmNearestTiesToEven);
9646 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9647 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009648 if (ResR.isNaN() && ResI.isNaN()) {
9649 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9650 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9651 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9652 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9653 D.isFinite()) {
9654 A = APFloat::copySign(
9655 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9656 B = APFloat::copySign(
9657 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9658 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9659 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9660 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9661 C = APFloat::copySign(
9662 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9663 D = APFloat::copySign(
9664 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9665 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9666 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9667 }
9668 }
9669 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009670 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009671 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9672 return Error(E, diag::note_expr_divide_by_zero);
9673
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009674 ComplexValue LHS = Result;
9675 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9676 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9677 Result.getComplexIntReal() =
9678 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9679 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9680 Result.getComplexIntImag() =
9681 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9682 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9683 }
9684 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009685 }
9686
John McCall93d91dc2010-05-07 17:22:02 +00009687 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009688}
9689
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009690bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9691 // Get the operand value into 'Result'.
9692 if (!Visit(E->getSubExpr()))
9693 return false;
9694
9695 switch (E->getOpcode()) {
9696 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009697 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009698 case UO_Extension:
9699 return true;
9700 case UO_Plus:
9701 // The result is always just the subexpr.
9702 return true;
9703 case UO_Minus:
9704 if (Result.isComplexFloat()) {
9705 Result.getComplexFloatReal().changeSign();
9706 Result.getComplexFloatImag().changeSign();
9707 }
9708 else {
9709 Result.getComplexIntReal() = -Result.getComplexIntReal();
9710 Result.getComplexIntImag() = -Result.getComplexIntImag();
9711 }
9712 return true;
9713 case UO_Not:
9714 if (Result.isComplexFloat())
9715 Result.getComplexFloatImag().changeSign();
9716 else
9717 Result.getComplexIntImag() = -Result.getComplexIntImag();
9718 return true;
9719 }
9720}
9721
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009722bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9723 if (E->getNumInits() == 2) {
9724 if (E->getType()->isComplexType()) {
9725 Result.makeComplexFloat();
9726 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9727 return false;
9728 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9729 return false;
9730 } else {
9731 Result.makeComplexInt();
9732 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9733 return false;
9734 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9735 return false;
9736 }
9737 return true;
9738 }
9739 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9740}
9741
Anders Carlsson537969c2008-11-16 20:27:53 +00009742//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009743// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9744// implicit conversion.
9745//===----------------------------------------------------------------------===//
9746
9747namespace {
9748class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009749 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009750 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +00009751 APValue &Result;
9752public:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009753 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9754 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +00009755
9756 bool Success(const APValue &V, const Expr *E) {
9757 Result = V;
9758 return true;
9759 }
9760
9761 bool ZeroInitialization(const Expr *E) {
9762 ImplicitValueInitExpr VIE(
9763 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009764 // For atomic-qualified class (and array) types in C++, initialize the
9765 // _Atomic-wrapped subobject directly, in-place.
9766 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9767 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +00009768 }
9769
9770 bool VisitCastExpr(const CastExpr *E) {
9771 switch (E->getCastKind()) {
9772 default:
9773 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9774 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009775 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9776 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +00009777 }
9778 }
9779};
9780} // end anonymous namespace
9781
Richard Smith64cb9ca2017-02-22 22:09:50 +00009782static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9783 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +00009784 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009785 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +00009786}
9787
9788//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009789// Void expression evaluation, primarily for a cast to void on the LHS of a
9790// comma operator
9791//===----------------------------------------------------------------------===//
9792
9793namespace {
9794class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009795 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009796public:
9797 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9798
Richard Smith2e312c82012-03-03 22:46:17 +00009799 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009800
9801 bool VisitCastExpr(const CastExpr *E) {
9802 switch (E->getCastKind()) {
9803 default:
9804 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9805 case CK_ToVoid:
9806 VisitIgnoredValue(E->getSubExpr());
9807 return true;
9808 }
9809 }
Hal Finkela8443c32014-07-17 14:49:58 +00009810
9811 bool VisitCallExpr(const CallExpr *E) {
9812 switch (E->getBuiltinCallee()) {
9813 default:
9814 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9815 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009816 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009817 // The argument is not evaluated!
9818 return true;
9819 }
9820 }
Richard Smith42d3af92011-12-07 00:43:50 +00009821};
9822} // end anonymous namespace
9823
9824static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9825 assert(E->isRValue() && E->getType()->isVoidType());
9826 return VoidExprEvaluator(Info).Visit(E);
9827}
9828
9829//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009830// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009831//===----------------------------------------------------------------------===//
9832
Richard Smith2e312c82012-03-03 22:46:17 +00009833static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009834 // In C, function designators are not lvalues, but we evaluate them as if they
9835 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009836 QualType T = E->getType();
9837 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009838 LValue LV;
9839 if (!EvaluateLValue(E, LV, Info))
9840 return false;
9841 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009842 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009843 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009844 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009845 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009846 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009847 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009848 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009849 LValue LV;
9850 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009851 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009852 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009853 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009854 llvm::APFloat F(0.0);
9855 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009856 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009857 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009858 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009859 ComplexValue C;
9860 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009861 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009862 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009863 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009864 MemberPtr P;
9865 if (!EvaluateMemberPointer(E, P, Info))
9866 return false;
9867 P.moveInto(Result);
9868 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009869 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009870 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009871 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009872 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9873 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009874 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009875 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009876 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009877 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009878 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009879 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9880 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009881 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009882 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009883 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009884 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009885 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009886 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009887 if (!EvaluateVoid(E, Info))
9888 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009889 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009890 QualType Unqual = T.getAtomicUnqualifiedType();
9891 if (Unqual->isArrayType() || Unqual->isRecordType()) {
9892 LValue LV;
9893 LV.set(E, Info.CurrentCall->Index);
9894 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9895 if (!EvaluateAtomic(E, &LV, Value, Info))
9896 return false;
9897 } else {
9898 if (!EvaluateAtomic(E, nullptr, Result, Info))
9899 return false;
9900 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009901 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009902 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009903 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009904 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009905 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009906 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009907 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009908
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009909 return true;
9910}
9911
Richard Smithb228a862012-02-15 02:18:13 +00009912/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9913/// cases, the in-place evaluation is essential, since later initializers for
9914/// an object can indirectly refer to subobjects which were initialized earlier.
9915static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009916 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009917 assert(!E->isValueDependent());
9918
Richard Smith7525ff62013-05-09 07:14:00 +00009919 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009920 return false;
9921
9922 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009923 // Evaluate arrays and record types in-place, so that later initializers can
9924 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +00009925 QualType T = E->getType();
9926 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +00009927 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00009928 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +00009929 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00009930 else if (T->isAtomicType()) {
9931 QualType Unqual = T.getAtomicUnqualifiedType();
9932 if (Unqual->isArrayType() || Unqual->isRecordType())
9933 return EvaluateAtomic(E, &This, Result, Info);
9934 }
Richard Smithed5165f2011-11-04 05:33:44 +00009935 }
9936
9937 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009938 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009939}
9940
Richard Smithf57d8cb2011-12-09 22:58:01 +00009941/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9942/// lvalue-to-rvalue cast if it is an lvalue.
9943static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009944 if (E->getType().isNull())
9945 return false;
9946
Nick Lewyckyc190f962017-05-02 01:06:16 +00009947 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +00009948 return false;
9949
Richard Smith2e312c82012-03-03 22:46:17 +00009950 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009951 return false;
9952
9953 if (E->isGLValue()) {
9954 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009955 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009956 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009957 return false;
9958 }
9959
Richard Smith2e312c82012-03-03 22:46:17 +00009960 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009961 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009962}
Richard Smith11562c52011-10-28 17:51:58 +00009963
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009964static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Nick Lewyckye7d6fbd2017-04-29 09:33:46 +00009965 const ASTContext &Ctx, bool &IsConst,
9966 bool IsCheckingForOverflow) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009967 // Fast-path evaluations of integer literals, since we sometimes see files
9968 // containing vast quantities of these.
9969 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9970 Result.Val = APValue(APSInt(L->getValue(),
9971 L->getType()->isUnsignedIntegerType()));
9972 IsConst = true;
9973 return true;
9974 }
James Dennett0492ef02014-03-14 17:44:10 +00009975
9976 // This case should be rare, but we need to check it before we check on
9977 // the type below.
9978 if (Exp->getType().isNull()) {
9979 IsConst = false;
9980 return true;
9981 }
Daniel Jasperffdee092017-05-02 19:21:42 +00009982
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009983 // FIXME: Evaluating values of large array and record types can cause
9984 // performance problems. Only do so in C++11 for now.
9985 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9986 Exp->getType()->isRecordType()) &&
Nick Lewyckye7d6fbd2017-04-29 09:33:46 +00009987 !Ctx.getLangOpts().CPlusPlus11 && !IsCheckingForOverflow) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009988 IsConst = false;
9989 return true;
9990 }
9991 return false;
9992}
9993
9994
Richard Smith7b553f12011-10-29 00:50:52 +00009995/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009996/// any crazy technique (that has nothing to do with language standards) that
9997/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009998/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9999/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +000010000bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010001 bool IsConst;
Nick Lewyckye7d6fbd2017-04-29 09:33:46 +000010002 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst, false))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010003 return IsConst;
Daniel Jasperffdee092017-05-02 19:21:42 +000010004
Richard Smith6d4c6582013-11-05 22:18:15 +000010005 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010006 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +000010007}
10008
Jay Foad39c79802011-01-12 09:06:06 +000010009bool Expr::EvaluateAsBooleanCondition(bool &Result,
10010 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010011 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010012 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010013 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010014}
10015
Richard Smithce8eca52015-12-08 03:21:47 +000010016static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10017 Expr::SideEffectsKind SEK) {
10018 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10019 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10020}
10021
Richard Smith5fab0c92011-12-28 19:48:30 +000010022bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10023 SideEffectsKind AllowSideEffects) const {
10024 if (!getType()->isIntegralOrEnumerationType())
10025 return false;
10026
Richard Smith11562c52011-10-28 17:51:58 +000010027 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010028 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +000010029 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010030 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010031
Richard Smith11562c52011-10-28 17:51:58 +000010032 Result = ExprResult.Val.getInt();
10033 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010034}
10035
Richard Trieube234c32016-04-21 21:04:55 +000010036bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10037 SideEffectsKind AllowSideEffects) const {
10038 if (!getType()->isRealFloatingType())
10039 return false;
10040
10041 EvalResult ExprResult;
10042 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10043 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10044 return false;
10045
10046 Result = ExprResult.Val.getFloat();
10047 return true;
10048}
10049
Jay Foad39c79802011-01-12 09:06:06 +000010050bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010051 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010052
John McCall45d55e42010-05-07 21:00:08 +000010053 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010054 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10055 !CheckLValueConstantExpression(Info, getExprLoc(),
10056 Ctx.getLValueReferenceType(getType()), LV))
10057 return false;
10058
Richard Smith2e312c82012-03-03 22:46:17 +000010059 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010060 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010061}
10062
Richard Smithd0b4dd62011-12-19 06:19:21 +000010063bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10064 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010065 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010066 // FIXME: Evaluating initializers for large array and record types can cause
10067 // performance problems. Only do so in C++11 for now.
10068 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010069 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010070 return false;
10071
Richard Smithd0b4dd62011-12-19 06:19:21 +000010072 Expr::EvalStatus EStatus;
10073 EStatus.Diag = &Notes;
10074
Richard Smith0c6124b2015-12-03 01:36:22 +000010075 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10076 ? EvalInfo::EM_ConstantExpression
10077 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010078 InitInfo.setEvaluatingDecl(VD, Value);
10079
10080 LValue LVal;
10081 LVal.set(VD);
10082
Richard Smithfddd3842011-12-30 21:15:51 +000010083 // C++11 [basic.start.init]p2:
10084 // Variables with static storage duration or thread storage duration shall be
10085 // zero-initialized before any other initialization takes place.
10086 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010087 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010088 !VD->getType()->isReferenceType()) {
10089 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010090 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010091 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010092 return false;
10093 }
10094
Richard Smith7525ff62013-05-09 07:14:00 +000010095 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10096 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010097 EStatus.HasSideEffects)
10098 return false;
10099
10100 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10101 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010102}
10103
Richard Smith7b553f12011-10-29 00:50:52 +000010104/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10105/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010106bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010107 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010108 return EvaluateAsRValue(Result, Ctx) &&
10109 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010110}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010111
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010112APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010113 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010114 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010115 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010116 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010117 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010118 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010119 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010120
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010121 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010122}
John McCall864e3962010-05-07 05:32:02 +000010123
Richard Smithe9ff7702013-11-05 22:23:30 +000010124void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010125 bool IsConst;
10126 EvalResult EvalResult;
Nick Lewyckye7d6fbd2017-04-29 09:33:46 +000010127 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst, true)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010128 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010129 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10130 }
10131}
10132
Richard Smithe6c01442013-06-05 00:46:14 +000010133bool Expr::EvalResult::isGlobalLValue() const {
10134 assert(Val.isLValue());
10135 return IsGlobalLValue(Val.getLValueBase());
10136}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010137
10138
John McCall864e3962010-05-07 05:32:02 +000010139/// isIntegerConstantExpr - this recursive routine will test if an expression is
10140/// an integer constant expression.
10141
10142/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10143/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010144
10145// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010146// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10147// and a (possibly null) SourceLocation indicating the location of the problem.
10148//
John McCall864e3962010-05-07 05:32:02 +000010149// Note that to reduce code duplication, this helper does no evaluation
10150// itself; the caller checks whether the expression is evaluatable, and
10151// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010152// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010153
Dan Gohman28ade552010-07-26 21:25:24 +000010154namespace {
10155
Richard Smith9e575da2012-12-28 13:25:52 +000010156enum ICEKind {
10157 /// This expression is an ICE.
10158 IK_ICE,
10159 /// This expression is not an ICE, but if it isn't evaluated, it's
10160 /// a legal subexpression for an ICE. This return value is used to handle
10161 /// the comma operator in C99 mode, and non-constant subexpressions.
10162 IK_ICEIfUnevaluated,
10163 /// This expression is not an ICE, and is not a legal subexpression for one.
10164 IK_NotICE
10165};
10166
John McCall864e3962010-05-07 05:32:02 +000010167struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010168 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010169 SourceLocation Loc;
10170
Richard Smith9e575da2012-12-28 13:25:52 +000010171 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010172};
10173
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010174}
Dan Gohman28ade552010-07-26 21:25:24 +000010175
Richard Smith9e575da2012-12-28 13:25:52 +000010176static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10177
10178static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010179
Craig Toppera31a8822013-08-22 07:09:37 +000010180static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010181 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010182 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010183 !EVResult.Val.isInt())
10184 return ICEDiag(IK_NotICE, E->getLocStart());
10185
John McCall864e3962010-05-07 05:32:02 +000010186 return NoDiag();
10187}
10188
Craig Toppera31a8822013-08-22 07:09:37 +000010189static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010190 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010191 if (!E->getType()->isIntegralOrEnumerationType())
10192 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010193
10194 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010195#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010196#define STMT(Node, Base) case Expr::Node##Class:
10197#define EXPR(Node, Base)
10198#include "clang/AST/StmtNodes.inc"
10199 case Expr::PredefinedExprClass:
10200 case Expr::FloatingLiteralClass:
10201 case Expr::ImaginaryLiteralClass:
10202 case Expr::StringLiteralClass:
10203 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010204 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010205 case Expr::MemberExprClass:
10206 case Expr::CompoundAssignOperatorClass:
10207 case Expr::CompoundLiteralExprClass:
10208 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010209 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010210 case Expr::ArrayInitLoopExprClass:
10211 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010212 case Expr::NoInitExprClass:
10213 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010214 case Expr::ImplicitValueInitExprClass:
10215 case Expr::ParenListExprClass:
10216 case Expr::VAArgExprClass:
10217 case Expr::AddrLabelExprClass:
10218 case Expr::StmtExprClass:
10219 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010220 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010221 case Expr::CXXDynamicCastExprClass:
10222 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010223 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010224 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010225 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010226 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010227 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010228 case Expr::CXXThisExprClass:
10229 case Expr::CXXThrowExprClass:
10230 case Expr::CXXNewExprClass:
10231 case Expr::CXXDeleteExprClass:
10232 case Expr::CXXPseudoDestructorExprClass:
10233 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010234 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010235 case Expr::DependentScopeDeclRefExprClass:
10236 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010237 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010238 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010239 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010240 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010241 case Expr::CXXTemporaryObjectExprClass:
10242 case Expr::CXXUnresolvedConstructExprClass:
10243 case Expr::CXXDependentScopeMemberExprClass:
10244 case Expr::UnresolvedMemberExprClass:
10245 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010246 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010247 case Expr::ObjCArrayLiteralClass:
10248 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010249 case Expr::ObjCEncodeExprClass:
10250 case Expr::ObjCMessageExprClass:
10251 case Expr::ObjCSelectorExprClass:
10252 case Expr::ObjCProtocolExprClass:
10253 case Expr::ObjCIvarRefExprClass:
10254 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010255 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010256 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010257 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010258 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010259 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010260 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010261 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010262 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010263 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010264 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010265 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010266 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010267 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010268 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010269 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010270 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010271 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010272 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010273 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000010274 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010275 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010276 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010277
Richard Smithf137f932014-01-25 20:50:08 +000010278 case Expr::InitListExprClass: {
10279 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10280 // form "T x = { a };" is equivalent to "T x = a;".
10281 // Unless we're initializing a reference, T is a scalar as it is known to be
10282 // of integral or enumeration type.
10283 if (E->isRValue())
10284 if (cast<InitListExpr>(E)->getNumInits() == 1)
10285 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10286 return ICEDiag(IK_NotICE, E->getLocStart());
10287 }
10288
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010289 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010290 case Expr::GNUNullExprClass:
10291 // GCC considers the GNU __null value to be an integral constant expression.
10292 return NoDiag();
10293
John McCall7c454bb2011-07-15 05:09:51 +000010294 case Expr::SubstNonTypeTemplateParmExprClass:
10295 return
10296 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10297
John McCall864e3962010-05-07 05:32:02 +000010298 case Expr::ParenExprClass:
10299 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010300 case Expr::GenericSelectionExprClass:
10301 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010302 case Expr::IntegerLiteralClass:
10303 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010304 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010305 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010306 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010307 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010308 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010309 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010310 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010311 return NoDiag();
10312 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010313 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010314 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10315 // constant expressions, but they can never be ICEs because an ICE cannot
10316 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010317 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010318 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010319 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010320 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010321 }
Richard Smith6365c912012-02-24 22:12:32 +000010322 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010323 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10324 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010325 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010326 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010327 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010328 // Parameter variables are never constants. Without this check,
10329 // getAnyInitializer() can find a default argument, which leads
10330 // to chaos.
10331 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010332 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010333
10334 // C++ 7.1.5.1p2
10335 // A variable of non-volatile const-qualified integral or enumeration
10336 // type initialized by an ICE can be used in ICEs.
10337 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010338 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010339 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010340
Richard Smithd0b4dd62011-12-19 06:19:21 +000010341 const VarDecl *VD;
10342 // Look for a declaration of this variable that has an initializer, and
10343 // check whether it is an ICE.
10344 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10345 return NoDiag();
10346 else
Richard Smith9e575da2012-12-28 13:25:52 +000010347 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010348 }
10349 }
Richard Smith9e575da2012-12-28 13:25:52 +000010350 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010351 }
John McCall864e3962010-05-07 05:32:02 +000010352 case Expr::UnaryOperatorClass: {
10353 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10354 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010355 case UO_PostInc:
10356 case UO_PostDec:
10357 case UO_PreInc:
10358 case UO_PreDec:
10359 case UO_AddrOf:
10360 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010361 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010362 // C99 6.6/3 allows increment and decrement within unevaluated
10363 // subexpressions of constant expressions, but they can never be ICEs
10364 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010365 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010366 case UO_Extension:
10367 case UO_LNot:
10368 case UO_Plus:
10369 case UO_Minus:
10370 case UO_Not:
10371 case UO_Real:
10372 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010373 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010374 }
Richard Smith9e575da2012-12-28 13:25:52 +000010375
John McCall864e3962010-05-07 05:32:02 +000010376 // OffsetOf falls through here.
10377 }
10378 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010379 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10380 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10381 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10382 // compliance: we should warn earlier for offsetof expressions with
10383 // array subscripts that aren't ICEs, and if the array subscripts
10384 // are ICEs, the value of the offsetof must be an integer constant.
10385 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010386 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010387 case Expr::UnaryExprOrTypeTraitExprClass: {
10388 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10389 if ((Exp->getKind() == UETT_SizeOf) &&
10390 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010391 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010392 return NoDiag();
10393 }
10394 case Expr::BinaryOperatorClass: {
10395 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10396 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010397 case BO_PtrMemD:
10398 case BO_PtrMemI:
10399 case BO_Assign:
10400 case BO_MulAssign:
10401 case BO_DivAssign:
10402 case BO_RemAssign:
10403 case BO_AddAssign:
10404 case BO_SubAssign:
10405 case BO_ShlAssign:
10406 case BO_ShrAssign:
10407 case BO_AndAssign:
10408 case BO_XorAssign:
10409 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000010410 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10411 // constant expressions, but they can never be ICEs because an ICE cannot
10412 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010413 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010414
John McCalle3027922010-08-25 11:45:40 +000010415 case BO_Mul:
10416 case BO_Div:
10417 case BO_Rem:
10418 case BO_Add:
10419 case BO_Sub:
10420 case BO_Shl:
10421 case BO_Shr:
10422 case BO_LT:
10423 case BO_GT:
10424 case BO_LE:
10425 case BO_GE:
10426 case BO_EQ:
10427 case BO_NE:
10428 case BO_And:
10429 case BO_Xor:
10430 case BO_Or:
10431 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010432 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10433 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010434 if (Exp->getOpcode() == BO_Div ||
10435 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010436 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010437 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010438 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010439 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010440 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010441 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010442 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010443 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010444 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010445 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010446 }
10447 }
10448 }
John McCalle3027922010-08-25 11:45:40 +000010449 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010450 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010451 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10452 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010453 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10454 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010455 } else {
10456 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010457 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010458 }
10459 }
Richard Smith9e575da2012-12-28 13:25:52 +000010460 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010461 }
John McCalle3027922010-08-25 11:45:40 +000010462 case BO_LAnd:
10463 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010464 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10465 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010466 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010467 // Rare case where the RHS has a comma "side-effect"; we need
10468 // to actually check the condition to see whether the side
10469 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010470 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010471 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010472 return RHSResult;
10473 return NoDiag();
10474 }
10475
Richard Smith9e575da2012-12-28 13:25:52 +000010476 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010477 }
10478 }
10479 }
10480 case Expr::ImplicitCastExprClass:
10481 case Expr::CStyleCastExprClass:
10482 case Expr::CXXFunctionalCastExprClass:
10483 case Expr::CXXStaticCastExprClass:
10484 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010485 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010486 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010487 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010488 if (isa<ExplicitCastExpr>(E)) {
10489 if (const FloatingLiteral *FL
10490 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10491 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10492 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10493 APSInt IgnoredVal(DestWidth, !DestSigned);
10494 bool Ignored;
10495 // If the value does not fit in the destination type, the behavior is
10496 // undefined, so we are not required to treat it as a constant
10497 // expression.
10498 if (FL->getValue().convertToInteger(IgnoredVal,
10499 llvm::APFloat::rmTowardZero,
10500 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010501 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010502 return NoDiag();
10503 }
10504 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010505 switch (cast<CastExpr>(E)->getCastKind()) {
10506 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010507 case CK_AtomicToNonAtomic:
10508 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010509 case CK_NoOp:
10510 case CK_IntegralToBoolean:
10511 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010512 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010513 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010514 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010515 }
John McCall864e3962010-05-07 05:32:02 +000010516 }
John McCallc07a0c72011-02-17 10:25:35 +000010517 case Expr::BinaryConditionalOperatorClass: {
10518 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10519 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010520 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010521 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010522 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10523 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10524 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010525 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010526 return FalseResult;
10527 }
John McCall864e3962010-05-07 05:32:02 +000010528 case Expr::ConditionalOperatorClass: {
10529 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10530 // If the condition (ignoring parens) is a __builtin_constant_p call,
10531 // then only the true side is actually considered in an integer constant
10532 // expression, and it is fully evaluated. This is an important GNU
10533 // extension. See GCC PR38377 for discussion.
10534 if (const CallExpr *CallCE
10535 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010536 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010537 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010538 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010539 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010540 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010541
Richard Smithf57d8cb2011-12-09 22:58:01 +000010542 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10543 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010544
Richard Smith9e575da2012-12-28 13:25:52 +000010545 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010546 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010547 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010548 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010549 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010550 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010551 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010552 return NoDiag();
10553 // Rare case where the diagnostics depend on which side is evaluated
10554 // Note that if we get here, CondResult is 0, and at least one of
10555 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010556 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010557 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010558 return TrueResult;
10559 }
10560 case Expr::CXXDefaultArgExprClass:
10561 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010562 case Expr::CXXDefaultInitExprClass:
10563 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010564 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010565 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010566 }
10567 }
10568
David Blaikiee4d798f2012-01-20 21:50:17 +000010569 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010570}
10571
Richard Smithf57d8cb2011-12-09 22:58:01 +000010572/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010573static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010574 const Expr *E,
10575 llvm::APSInt *Value,
10576 SourceLocation *Loc) {
10577 if (!E->getType()->isIntegralOrEnumerationType()) {
10578 if (Loc) *Loc = E->getExprLoc();
10579 return false;
10580 }
10581
Richard Smith66e05fe2012-01-18 05:21:49 +000010582 APValue Result;
10583 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010584 return false;
10585
Richard Smith98710fc2014-11-13 23:03:19 +000010586 if (!Result.isInt()) {
10587 if (Loc) *Loc = E->getExprLoc();
10588 return false;
10589 }
10590
Richard Smith66e05fe2012-01-18 05:21:49 +000010591 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010592 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010593}
10594
Craig Toppera31a8822013-08-22 07:09:37 +000010595bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10596 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010597 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010598 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010599
Richard Smith9e575da2012-12-28 13:25:52 +000010600 ICEDiag D = CheckICE(this, Ctx);
10601 if (D.Kind != IK_ICE) {
10602 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010603 return false;
10604 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010605 return true;
10606}
10607
Craig Toppera31a8822013-08-22 07:09:37 +000010608bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010609 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010610 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010611 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10612
10613 if (!isIntegerConstantExpr(Ctx, Loc))
10614 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010615 // The only possible side-effects here are due to UB discovered in the
10616 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10617 // required to treat the expression as an ICE, so we produce the folded
10618 // value.
10619 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010620 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010621 return true;
10622}
Richard Smith66e05fe2012-01-18 05:21:49 +000010623
Craig Toppera31a8822013-08-22 07:09:37 +000010624bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010625 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010626}
10627
Craig Toppera31a8822013-08-22 07:09:37 +000010628bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010629 SourceLocation *Loc) const {
10630 // We support this checking in C++98 mode in order to diagnose compatibility
10631 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010632 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010633
Richard Smith98a0a492012-02-14 21:38:30 +000010634 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010635 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010636 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010637 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010638 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010639
10640 APValue Scratch;
10641 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10642
10643 if (!Diags.empty()) {
10644 IsConstExpr = false;
10645 if (Loc) *Loc = Diags[0].first;
10646 } else if (!IsConstExpr) {
10647 // FIXME: This shouldn't happen.
10648 if (Loc) *Loc = getExprLoc();
10649 }
10650
10651 return IsConstExpr;
10652}
Richard Smith253c2a32012-01-27 01:14:48 +000010653
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010654bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10655 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010656 ArrayRef<const Expr*> Args,
10657 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010658 Expr::EvalStatus Status;
10659 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10660
George Burgess IV177399e2017-01-09 04:12:14 +000010661 LValue ThisVal;
10662 const LValue *ThisPtr = nullptr;
10663 if (This) {
10664#ifndef NDEBUG
10665 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10666 assert(MD && "Don't provide `this` for non-methods.");
10667 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10668#endif
10669 if (EvaluateObjectArgument(Info, This, ThisVal))
10670 ThisPtr = &ThisVal;
10671 if (Info.EvalStatus.HasSideEffects)
10672 return false;
10673 }
10674
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010675 ArgVector ArgValues(Args.size());
10676 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10677 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010678 if ((*I)->isValueDependent() ||
10679 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010680 // If evaluation fails, throw away the argument entirely.
10681 ArgValues[I - Args.begin()] = APValue();
10682 if (Info.EvalStatus.HasSideEffects)
10683 return false;
10684 }
10685
10686 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010687 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010688 ArgValues.data());
10689 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10690}
10691
Richard Smith253c2a32012-01-27 01:14:48 +000010692bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010693 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010694 PartialDiagnosticAt> &Diags) {
10695 // FIXME: It would be useful to check constexpr function templates, but at the
10696 // moment the constant expression evaluator cannot cope with the non-rigorous
10697 // ASTs which we build for dependent expressions.
10698 if (FD->isDependentContext())
10699 return true;
10700
10701 Expr::EvalStatus Status;
10702 Status.Diag = &Diags;
10703
Richard Smith6d4c6582013-11-05 22:18:15 +000010704 EvalInfo Info(FD->getASTContext(), Status,
10705 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010706
10707 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010708 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010709
Richard Smith7525ff62013-05-09 07:14:00 +000010710 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010711 // is a temporary being used as the 'this' pointer.
10712 LValue This;
10713 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010714 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010715
Richard Smith253c2a32012-01-27 01:14:48 +000010716 ArrayRef<const Expr*> Args;
10717
Richard Smith2e312c82012-03-03 22:46:17 +000010718 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010719 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10720 // Evaluate the call as a constant initializer, to allow the construction
10721 // of objects of non-literal types.
10722 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010723 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10724 } else {
10725 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010726 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010727 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010728 }
Richard Smith253c2a32012-01-27 01:14:48 +000010729
10730 return Diags.empty();
10731}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010732
10733bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10734 const FunctionDecl *FD,
10735 SmallVectorImpl<
10736 PartialDiagnosticAt> &Diags) {
10737 Expr::EvalStatus Status;
10738 Status.Diag = &Diags;
10739
10740 EvalInfo Info(FD->getASTContext(), Status,
10741 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10742
10743 // Fabricate a call stack frame to give the arguments a plausible cover story.
10744 ArrayRef<const Expr*> Args;
10745 ArgVector ArgValues(0);
10746 bool Success = EvaluateArgs(Args, ArgValues, Info);
10747 (void)Success;
10748 assert(Success &&
10749 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010750 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010751
10752 APValue ResultScratch;
10753 Evaluate(ResultScratch, Info, E);
10754 return Diags.empty();
10755}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010756
10757bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10758 unsigned Type) const {
10759 if (!getType()->isPointerType())
10760 return false;
10761
10762 Expr::EvalStatus Status;
10763 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010764 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010765}