blob: 1bb252d2d1ce7de4b44cbd99d9de676f3974e9f3 [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,
151 uint64_t &ArraySize, QualType &Type, bool &IsArray) {
152 // 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) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000160 if (Type->isArrayType()) {
161 const ConstantArrayType *CAT =
George Burgess IVe3763372016-12-22 02:50:20 +0000162 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
Richard Smitha8105bc2012-01-06 16:39:00 +0000163 Type = CAT->getElementType();
164 ArraySize = CAT->getSize().getZExtValue();
165 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
George Burgess IVe3763372016-12-22 02:50:20 +0000203 /// Indicator of whether the first entry is an unsized array.
204 unsigned FirstEntryIsAnUnsizedArray : 1;
205
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),
George Burgess IVe3763372016-12-22 02:50:20 +0000234 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
235 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),
George Burgess IVe3763372016-12-22 02:50:20 +0000240 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
241 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());
George Burgess IVa51c4072015-10-16 01:49:01 +0000247 if (V.getLValueBase()) {
248 bool IsArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000249 MostDerivedPathLength = findMostDerivedSubobject(
250 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
251 MostDerivedType, IsArray);
George Burgess IVa51c4072015-10-16 01:49:01 +0000252 MostDerivedIsArrayElement = IsArray;
253 }
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");
266 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
267 }
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 }
Richard Smithd6cc1982017-01-31 02:23:02 +0000353 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, APSInt N);
Richard Smith96e0c102011-11-04 02:25:55 +0000354 /// Add N to the address of this subobject.
Richard Smithd6cc1982017-01-31 02:23:02 +0000355 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
356 if (Invalid || !N) return;
357 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
George Burgess IVe3763372016-12-22 02:50:20 +0000358 if (isMostDerivedAnUnsizedArray()) {
359 // Can't verify -- trust that the user is doing the right thing (or if
360 // not, trust that the caller will catch the bad behavior).
Richard Smithd6cc1982017-01-31 02:23:02 +0000361 // FIXME: Should we reject if this overflows, at least?
362 Entries.back().ArrayIndex += TruncatedN;
George Burgess IVe3763372016-12-22 02:50:20 +0000363 return;
364 }
Richard Smithd6cc1982017-01-31 02:23:02 +0000365
Richard Smitha8105bc2012-01-06 16:39:00 +0000366 // [expr.add]p4: For the purposes of these operators, a pointer to a
367 // nonarray object behaves the same as a pointer to the first element of
368 // an array of length one with the type of the object as its element type.
Richard Smithd6cc1982017-01-31 02:23:02 +0000369 bool IsArray = MostDerivedPathLength == Entries.size() &&
370 MostDerivedIsArrayElement;
371 uint64_t ArrayIndex =
372 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
373 uint64_t ArraySize =
374 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
375
376 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
377 // Calculate the actual index in a wide enough type, so we can include
378 // it in the note.
379 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
380 (llvm::APInt&)N += ArrayIndex;
381 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
382 diagnosePointerArithmetic(Info, E, N);
Richard Smith96e0c102011-11-04 02:25:55 +0000383 setInvalid();
Richard Smithd6cc1982017-01-31 02:23:02 +0000384 return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000385 }
Richard Smithd6cc1982017-01-31 02:23:02 +0000386
387 ArrayIndex += TruncatedN;
388 assert(ArrayIndex <= ArraySize &&
389 "bounds check succeeded for out-of-bounds index");
390
391 if (IsArray)
392 Entries.back().ArrayIndex = ArrayIndex;
393 else
394 IsOnePastTheEnd = (ArrayIndex != 0);
Richard Smith96e0c102011-11-04 02:25:55 +0000395 }
396 };
397
Richard Smith254a73d2011-10-28 22:34:42 +0000398 /// A stack frame in the constexpr call stack.
399 struct CallStackFrame {
400 EvalInfo &Info;
401
402 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000403 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000404
Richard Smithf6f003a2011-12-16 19:06:07 +0000405 /// Callee - The function which was called.
406 const FunctionDecl *Callee;
407
Richard Smithd62306a2011-11-10 06:34:14 +0000408 /// This - The binding for the this pointer in this call, if any.
409 const LValue *This;
410
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000411 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000412 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000413 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000414
Eli Friedman4830ec82012-06-25 21:21:08 +0000415 // Note that we intentionally use std::map here so that references to
416 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000417 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000418 typedef MapTy::const_iterator temp_iterator;
419 /// Temporaries - Temporary lvalues materialized within this stack frame.
420 MapTy Temporaries;
421
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000422 /// CallLoc - The location of the call expression for this call.
423 SourceLocation CallLoc;
424
425 /// Index - The call index of this call.
426 unsigned Index;
427
Faisal Vali051e3a22017-02-16 04:12:21 +0000428 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
429 // on the overall stack usage of deeply-recursing constexpr evaluataions.
430 // (We should cache this map rather than recomputing it repeatedly.)
431 // But let's try this and see how it goes; we can look into caching the map
432 // as a later change.
433
434 /// LambdaCaptureFields - Mapping from captured variables/this to
435 /// corresponding data members in the closure class.
436 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
437 FieldDecl *LambdaThisCaptureField;
438
Richard Smithf6f003a2011-12-16 19:06:07 +0000439 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
440 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000441 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000442 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000443
444 APValue *getTemporary(const void *Key) {
445 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000446 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000447 }
448 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000449 };
450
Richard Smith852c9db2013-04-20 22:23:05 +0000451 /// Temporarily override 'this'.
452 class ThisOverrideRAII {
453 public:
454 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
455 : Frame(Frame), OldThis(Frame.This) {
456 if (Enable)
457 Frame.This = NewThis;
458 }
459 ~ThisOverrideRAII() {
460 Frame.This = OldThis;
461 }
462 private:
463 CallStackFrame &Frame;
464 const LValue *OldThis;
465 };
466
Richard Smith92b1ce02011-12-12 09:28:41 +0000467 /// A partial diagnostic which we might know in advance that we are not going
468 /// to emit.
469 class OptionalDiagnostic {
470 PartialDiagnostic *Diag;
471
472 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000473 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
474 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000475
476 template<typename T>
477 OptionalDiagnostic &operator<<(const T &v) {
478 if (Diag)
479 *Diag << v;
480 return *this;
481 }
Richard Smithfe800032012-01-31 04:08:20 +0000482
483 OptionalDiagnostic &operator<<(const APSInt &I) {
484 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000485 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000486 I.toString(Buffer);
487 *Diag << StringRef(Buffer.data(), Buffer.size());
488 }
489 return *this;
490 }
491
492 OptionalDiagnostic &operator<<(const APFloat &F) {
493 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000494 // FIXME: Force the precision of the source value down so we don't
495 // print digits which are usually useless (we don't really care here if
496 // we truncate a digit by accident in edge cases). Ideally,
497 // APFloat::toString would automatically print the shortest
498 // representation which rounds to the correct value, but it's a bit
499 // tricky to implement.
500 unsigned precision =
501 llvm::APFloat::semanticsPrecision(F.getSemantics());
502 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000503 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000504 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000505 *Diag << StringRef(Buffer.data(), Buffer.size());
506 }
507 return *this;
508 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000509 };
510
Richard Smith08d6a2c2013-07-24 07:11:57 +0000511 /// A cleanup, and a flag indicating whether it is lifetime-extended.
512 class Cleanup {
513 llvm::PointerIntPair<APValue*, 1, bool> Value;
514
515 public:
516 Cleanup(APValue *Val, bool IsLifetimeExtended)
517 : Value(Val, IsLifetimeExtended) {}
518
519 bool isLifetimeExtended() const { return Value.getInt(); }
520 void endLifetime() {
521 *Value.getPointer() = APValue();
522 }
523 };
524
Richard Smithb228a862012-02-15 02:18:13 +0000525 /// EvalInfo - This is a private struct used by the evaluator to capture
526 /// information about a subexpression as it is folded. It retains information
527 /// about the AST context, but also maintains information about the folded
528 /// expression.
529 ///
530 /// If an expression could be evaluated, it is still possible it is not a C
531 /// "integer constant expression" or constant expression. If not, this struct
532 /// captures information about how and why not.
533 ///
534 /// One bit of information passed *into* the request for constant folding
535 /// indicates whether the subexpression is "evaluated" or not according to C
536 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
537 /// evaluate the expression regardless of what the RHS is, but C only allows
538 /// certain things in certain situations.
Reid Kleckner06df4022016-12-13 19:48:32 +0000539 struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000540 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000541
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000542 /// EvalStatus - Contains information about the evaluation.
543 Expr::EvalStatus &EvalStatus;
544
545 /// CurrentCall - The top of the constexpr call stack.
546 CallStackFrame *CurrentCall;
547
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000548 /// CallStackDepth - The number of calls in the call stack right now.
549 unsigned CallStackDepth;
550
Richard Smithb228a862012-02-15 02:18:13 +0000551 /// NextCallIndex - The next call index to assign.
552 unsigned NextCallIndex;
553
Richard Smitha3d3bd22013-05-08 02:12:03 +0000554 /// StepsLeft - The remaining number of evaluation steps we're permitted
555 /// to perform. This is essentially a limit for the number of statements
556 /// we will evaluate.
557 unsigned StepsLeft;
558
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000559 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000560 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000561 CallStackFrame BottomFrame;
562
Richard Smith08d6a2c2013-07-24 07:11:57 +0000563 /// A stack of values whose lifetimes end at the end of some surrounding
564 /// evaluation frame.
565 llvm::SmallVector<Cleanup, 16> CleanupStack;
566
Richard Smithd62306a2011-11-10 06:34:14 +0000567 /// EvaluatingDecl - This is the declaration whose initializer is being
568 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000569 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000570
571 /// EvaluatingDeclValue - This is the value being constructed for the
572 /// declaration whose initializer is being evaluated, if any.
573 APValue *EvaluatingDeclValue;
574
Richard Smith410306b2016-12-12 02:53:20 +0000575 /// The current array initialization index, if we're performing array
576 /// initialization.
577 uint64_t ArrayInitIndex = -1;
578
Richard Smith357362d2011-12-13 06:39:58 +0000579 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
580 /// notes attached to it will also be stored, otherwise they will not be.
581 bool HasActiveDiagnostic;
582
Richard Smith0c6124b2015-12-03 01:36:22 +0000583 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
584 /// fold (not just why it's not strictly a constant expression)?
585 bool HasFoldFailureDiagnostic;
586
George Burgess IV8c892b52016-05-25 22:31:54 +0000587 /// \brief Whether or not we're currently speculatively evaluating.
588 bool IsSpeculativelyEvaluating;
589
Richard Smith6d4c6582013-11-05 22:18:15 +0000590 enum EvaluationMode {
591 /// Evaluate as a constant expression. Stop if we find that the expression
592 /// is not a constant expression.
593 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000594
Richard Smith6d4c6582013-11-05 22:18:15 +0000595 /// Evaluate as a potential constant expression. Keep going if we hit a
596 /// construct that we can't evaluate yet (because we don't yet know the
597 /// value of something) but stop if we hit something that could never be
598 /// a constant expression.
599 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000600
Richard Smith6d4c6582013-11-05 22:18:15 +0000601 /// Fold the expression to a constant. Stop if we hit a side-effect that
602 /// we can't model.
603 EM_ConstantFold,
604
605 /// Evaluate the expression looking for integer overflow and similar
606 /// issues. Don't worry about side-effects, and try to visit all
607 /// subexpressions.
608 EM_EvaluateForOverflow,
609
610 /// Evaluate in any way we know how. Don't worry about side-effects that
611 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000612 EM_IgnoreSideEffects,
613
614 /// Evaluate as a constant expression. Stop if we find that the expression
615 /// is not a constant expression. Some expressions can be retried in the
616 /// optimizer if we don't constant fold them here, but in an unevaluated
617 /// context we try to fold them immediately since the optimizer never
618 /// gets a chance to look at it.
619 EM_ConstantExpressionUnevaluated,
620
621 /// Evaluate as a potential constant expression. Keep going if we hit a
622 /// construct that we can't evaluate yet (because we don't yet know the
623 /// value of something) but stop if we hit something that could never be
624 /// a constant expression. Some expressions can be retried in the
625 /// optimizer if we don't constant fold them here, but in an unevaluated
626 /// context we try to fold them immediately since the optimizer never
627 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000628 EM_PotentialConstantExpressionUnevaluated,
629
George Burgess IVf9013bf2017-02-10 22:52:29 +0000630 /// Evaluate as a constant expression. In certain scenarios, if:
631 /// - we find a MemberExpr with a base that can't be evaluated, or
632 /// - we find a variable initialized with a call to a function that has
633 /// the alloc_size attribute on it
634 /// then we may consider evaluation to have succeeded.
635 ///
George Burgess IVe3763372016-12-22 02:50:20 +0000636 /// In either case, the LValue returned shall have an invalid base; in the
637 /// former, the base will be the invalid MemberExpr, in the latter, the
638 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
639 /// said CallExpr.
640 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000641 } EvalMode;
642
643 /// Are we checking whether the expression is a potential constant
644 /// expression?
645 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000646 return EvalMode == EM_PotentialConstantExpression ||
647 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000648 }
649
650 /// Are we checking an expression for overflow?
651 // FIXME: We should check for any kind of undefined or suspicious behavior
652 // in such constructs, not just overflow.
653 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
654
655 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000656 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000657 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000658 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000659 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
660 EvaluatingDecl((const ValueDecl *)nullptr),
661 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000662 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
663 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000664
Richard Smith7525ff62013-05-09 07:14:00 +0000665 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
666 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000667 EvaluatingDeclValue = &Value;
668 }
669
David Blaikiebbafb8a2012-03-11 07:00:24 +0000670 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000671
Richard Smith357362d2011-12-13 06:39:58 +0000672 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000673 // Don't perform any constexpr calls (other than the call we're checking)
674 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000675 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000676 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000677 if (NextCallIndex == 0) {
678 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000679 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000680 return false;
681 }
Richard Smith357362d2011-12-13 06:39:58 +0000682 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
683 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000684 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000685 << getLangOpts().ConstexprCallDepth;
686 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000687 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000688
Richard Smithb228a862012-02-15 02:18:13 +0000689 CallStackFrame *getCallFrame(unsigned CallIndex) {
690 assert(CallIndex && "no call index in getCallFrame");
691 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
692 // be null in this loop.
693 CallStackFrame *Frame = CurrentCall;
694 while (Frame->Index > CallIndex)
695 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000696 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000697 }
698
Richard Smitha3d3bd22013-05-08 02:12:03 +0000699 bool nextStep(const Stmt *S) {
700 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000701 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000702 return false;
703 }
704 --StepsLeft;
705 return true;
706 }
707
Richard Smith357362d2011-12-13 06:39:58 +0000708 private:
709 /// Add a diagnostic to the diagnostics list.
710 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
711 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
712 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
713 return EvalStatus.Diag->back().second;
714 }
715
Richard Smithf6f003a2011-12-16 19:06:07 +0000716 /// Add notes containing a call stack to the current point of evaluation.
717 void addCallStack(unsigned Limit);
718
Faisal Valie690b7a2016-07-02 22:34:24 +0000719 private:
720 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
721 unsigned ExtraNotes, bool IsCCEDiag) {
722
Richard Smith92b1ce02011-12-12 09:28:41 +0000723 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000724 // If we have a prior diagnostic, it will be noting that the expression
725 // isn't a constant expression. This diagnostic is more important,
726 // unless we require this evaluation to produce a constant expression.
727 //
728 // FIXME: We might want to show both diagnostics to the user in
729 // EM_ConstantFold mode.
730 if (!EvalStatus.Diag->empty()) {
731 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000732 case EM_ConstantFold:
733 case EM_IgnoreSideEffects:
734 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000735 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000736 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000737 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000738 case EM_ConstantExpression:
739 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000740 case EM_ConstantExpressionUnevaluated:
741 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000742 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000743 HasActiveDiagnostic = false;
744 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000745 }
746 }
747
Richard Smithf6f003a2011-12-16 19:06:07 +0000748 unsigned CallStackNotes = CallStackDepth - 1;
749 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
750 if (Limit)
751 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000752 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000753 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000754
Richard Smith357362d2011-12-13 06:39:58 +0000755 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000756 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000757 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000758 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
759 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000760 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000761 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000762 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000763 }
Richard Smith357362d2011-12-13 06:39:58 +0000764 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000765 return OptionalDiagnostic();
766 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000767 public:
768 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
769 OptionalDiagnostic
770 FFDiag(SourceLocation Loc,
771 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
772 unsigned ExtraNotes = 0) {
773 return Diag(Loc, DiagId, ExtraNotes, false);
774 }
775
776 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000777 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000778 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000779 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000780 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000781 HasActiveDiagnostic = false;
782 return OptionalDiagnostic();
783 }
784
Richard Smith92b1ce02011-12-12 09:28:41 +0000785 /// Diagnose that the evaluation does not produce a C++11 core constant
786 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000787 ///
788 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
789 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000790 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000791 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000792 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000793 // Don't override a previous diagnostic. Don't bother collecting
794 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000795 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000796 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000797 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000798 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000799 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000800 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000801 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
802 = diag::note_invalid_subexpr_in_const_expr,
803 unsigned ExtraNotes = 0) {
804 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
805 }
Richard Smith357362d2011-12-13 06:39:58 +0000806 /// Add a note to a prior diagnostic.
807 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
808 if (!HasActiveDiagnostic)
809 return OptionalDiagnostic();
810 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000811 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000812
813 /// Add a stack of notes to a prior diagnostic.
814 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
815 if (HasActiveDiagnostic) {
816 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
817 Diags.begin(), Diags.end());
818 }
819 }
Richard Smith253c2a32012-01-27 01:14:48 +0000820
Richard Smith6d4c6582013-11-05 22:18:15 +0000821 /// Should we continue evaluation after encountering a side-effect that we
822 /// couldn't model?
823 bool keepEvaluatingAfterSideEffect() {
824 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000825 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000826 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000827 case EM_EvaluateForOverflow:
828 case EM_IgnoreSideEffects:
829 return true;
830
Richard Smith6d4c6582013-11-05 22:18:15 +0000831 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000832 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000833 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000834 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000835 return false;
836 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000837 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000838 }
839
840 /// Note that we have had a side-effect, and determine whether we should
841 /// keep evaluating.
842 bool noteSideEffect() {
843 EvalStatus.HasSideEffects = true;
844 return keepEvaluatingAfterSideEffect();
845 }
846
Richard Smithce8eca52015-12-08 03:21:47 +0000847 /// Should we continue evaluation after encountering undefined behavior?
848 bool keepEvaluatingAfterUndefinedBehavior() {
849 switch (EvalMode) {
850 case EM_EvaluateForOverflow:
851 case EM_IgnoreSideEffects:
852 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000853 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000854 return true;
855
856 case EM_PotentialConstantExpression:
857 case EM_PotentialConstantExpressionUnevaluated:
858 case EM_ConstantExpression:
859 case EM_ConstantExpressionUnevaluated:
860 return false;
861 }
862 llvm_unreachable("Missed EvalMode case");
863 }
864
865 /// Note that we hit something that was technically undefined behavior, but
866 /// that we can evaluate past it (such as signed overflow or floating-point
867 /// division by zero.)
868 bool noteUndefinedBehavior() {
869 EvalStatus.HasUndefinedBehavior = true;
870 return keepEvaluatingAfterUndefinedBehavior();
871 }
872
Richard Smith253c2a32012-01-27 01:14:48 +0000873 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000874 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000875 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000876 if (!StepsLeft)
877 return false;
878
879 switch (EvalMode) {
880 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000881 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000882 case EM_EvaluateForOverflow:
883 return true;
884
885 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000886 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000887 case EM_ConstantFold:
888 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000889 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000890 return false;
891 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000892 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000893 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000894
George Burgess IV8c892b52016-05-25 22:31:54 +0000895 /// Notes that we failed to evaluate an expression that other expressions
896 /// directly depend on, and determine if we should keep evaluating. This
897 /// should only be called if we actually intend to keep evaluating.
898 ///
899 /// Call noteSideEffect() instead if we may be able to ignore the value that
900 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
901 ///
902 /// (Foo(), 1) // use noteSideEffect
903 /// (Foo() || true) // use noteSideEffect
904 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000905 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000906 // Failure when evaluating some expression often means there is some
907 // subexpression whose evaluation was skipped. Therefore, (because we
908 // don't track whether we skipped an expression when unwinding after an
909 // evaluation failure) every evaluation failure that bubbles up from a
910 // subexpression implies that a side-effect has potentially happened. We
911 // skip setting the HasSideEffects flag to true until we decide to
912 // continue evaluating after that point, which happens here.
913 bool KeepGoing = keepEvaluatingAfterFailure();
914 EvalStatus.HasSideEffects |= KeepGoing;
915 return KeepGoing;
916 }
917
Richard Smith410306b2016-12-12 02:53:20 +0000918 class ArrayInitLoopIndex {
919 EvalInfo &Info;
920 uint64_t OuterIndex;
921
922 public:
923 ArrayInitLoopIndex(EvalInfo &Info)
924 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
925 Info.ArrayInitIndex = 0;
926 }
927 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
928
929 operator uint64_t&() { return Info.ArrayInitIndex; }
930 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000931 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000932
933 /// Object used to treat all foldable expressions as constant expressions.
934 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000935 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000936 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000937 bool HadNoPriorDiags;
938 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000939
Richard Smith6d4c6582013-11-05 22:18:15 +0000940 explicit FoldConstant(EvalInfo &Info, bool Enabled)
941 : Info(Info),
942 Enabled(Enabled),
943 HadNoPriorDiags(Info.EvalStatus.Diag &&
944 Info.EvalStatus.Diag->empty() &&
945 !Info.EvalStatus.HasSideEffects),
946 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000947 if (Enabled &&
948 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
949 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000950 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000951 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000952 void keepDiagnostics() { Enabled = false; }
953 ~FoldConstant() {
954 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000955 !Info.EvalStatus.HasSideEffects)
956 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000957 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000958 }
959 };
Richard Smith17100ba2012-02-16 02:46:34 +0000960
George Burgess IV3a03fab2015-09-04 21:28:13 +0000961 /// RAII object used to treat the current evaluation as the correct pointer
962 /// offset fold for the current EvalMode
963 struct FoldOffsetRAII {
964 EvalInfo &Info;
965 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +0000966 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +0000967 : Info(Info), OldMode(Info.EvalMode) {
968 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +0000969 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000970 }
971
972 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
973 };
974
George Burgess IV8c892b52016-05-25 22:31:54 +0000975 /// RAII object used to optionally suppress diagnostics and side-effects from
976 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000977 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000978 /// Pair of EvalInfo, and a bit that stores whether or not we were
979 /// speculatively evaluating when we created this RAII.
980 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000981 Expr::EvalStatus Old;
982
George Burgess IV8c892b52016-05-25 22:31:54 +0000983 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
984 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
985 Old = Other.Old;
986 Other.InfoAndOldSpecEval.setPointer(nullptr);
987 }
988
989 void maybeRestoreState() {
990 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
991 if (!Info)
992 return;
993
994 Info->EvalStatus = Old;
995 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
996 }
997
Richard Smith17100ba2012-02-16 02:46:34 +0000998 public:
George Burgess IV8c892b52016-05-25 22:31:54 +0000999 SpeculativeEvaluationRAII() = default;
1000
1001 SpeculativeEvaluationRAII(
1002 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1003 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
1004 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +00001005 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001006 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001007 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001008
1009 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1010 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1011 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001012 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001013
1014 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1015 maybeRestoreState();
1016 moveFromAndCancel(std::move(Other));
1017 return *this;
1018 }
1019
1020 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001021 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001022
1023 /// RAII object wrapping a full-expression or block scope, and handling
1024 /// the ending of the lifetime of temporaries created within it.
1025 template<bool IsFullExpression>
1026 class ScopeRAII {
1027 EvalInfo &Info;
1028 unsigned OldStackSize;
1029 public:
1030 ScopeRAII(EvalInfo &Info)
1031 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1032 ~ScopeRAII() {
1033 // Body moved to a static method to encourage the compiler to inline away
1034 // instances of this class.
1035 cleanup(Info, OldStackSize);
1036 }
1037 private:
1038 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1039 unsigned NewEnd = OldStackSize;
1040 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1041 I != N; ++I) {
1042 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1043 // Full-expression cleanup of a lifetime-extended temporary: nothing
1044 // to do, just move this cleanup to the right place in the stack.
1045 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1046 ++NewEnd;
1047 } else {
1048 // End the lifetime of the object.
1049 Info.CleanupStack[I].endLifetime();
1050 }
1051 }
1052 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1053 Info.CleanupStack.end());
1054 }
1055 };
1056 typedef ScopeRAII<false> BlockScopeRAII;
1057 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001058}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001059
Richard Smitha8105bc2012-01-06 16:39:00 +00001060bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1061 CheckSubobjectKind CSK) {
1062 if (Invalid)
1063 return false;
1064 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001065 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001066 << CSK;
1067 setInvalid();
1068 return false;
1069 }
1070 return true;
1071}
1072
1073void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Richard Smithd6cc1982017-01-31 02:23:02 +00001074 const Expr *E, APSInt N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001075 // If we're complaining, we must be able to statically determine the size of
1076 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001077 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001078 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001079 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001080 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001081 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001082 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001083 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001084 setInvalid();
1085}
1086
Richard Smithf6f003a2011-12-16 19:06:07 +00001087CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1088 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001089 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001090 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1091 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001092 Info.CurrentCall = this;
1093 ++Info.CallStackDepth;
1094}
1095
1096CallStackFrame::~CallStackFrame() {
1097 assert(Info.CurrentCall == this && "calls retired out of order");
1098 --Info.CallStackDepth;
1099 Info.CurrentCall = Caller;
1100}
1101
Richard Smith08d6a2c2013-07-24 07:11:57 +00001102APValue &CallStackFrame::createTemporary(const void *Key,
1103 bool IsLifetimeExtended) {
1104 APValue &Result = Temporaries[Key];
1105 assert(Result.isUninit() && "temporary created multiple times");
1106 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1107 return Result;
1108}
1109
Richard Smith84401042013-06-03 05:03:02 +00001110static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001111
1112void EvalInfo::addCallStack(unsigned Limit) {
1113 // Determine which calls to skip, if any.
1114 unsigned ActiveCalls = CallStackDepth - 1;
1115 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1116 if (Limit && Limit < ActiveCalls) {
1117 SkipStart = Limit / 2 + Limit % 2;
1118 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001119 }
1120
Richard Smithf6f003a2011-12-16 19:06:07 +00001121 // Walk the call stack and add the diagnostics.
1122 unsigned CallIdx = 0;
1123 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1124 Frame = Frame->Caller, ++CallIdx) {
1125 // Skip this call?
1126 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1127 if (CallIdx == SkipStart) {
1128 // Note that we're skipping calls.
1129 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1130 << unsigned(ActiveCalls - Limit);
1131 }
1132 continue;
1133 }
1134
Richard Smith5179eb72016-06-28 19:03:57 +00001135 // Use a different note for an inheriting constructor, because from the
1136 // user's perspective it's not really a function at all.
1137 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1138 if (CD->isInheritingConstructor()) {
1139 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1140 << CD->getParent();
1141 continue;
1142 }
1143 }
1144
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001145 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001146 llvm::raw_svector_ostream Out(Buffer);
1147 describeCall(Frame, Out);
1148 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1149 }
1150}
1151
1152namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001153 struct ComplexValue {
1154 private:
1155 bool IsInt;
1156
1157 public:
1158 APSInt IntReal, IntImag;
1159 APFloat FloatReal, FloatImag;
1160
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001161 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001162
1163 void makeComplexFloat() { IsInt = false; }
1164 bool isComplexFloat() const { return !IsInt; }
1165 APFloat &getComplexFloatReal() { return FloatReal; }
1166 APFloat &getComplexFloatImag() { return FloatImag; }
1167
1168 void makeComplexInt() { IsInt = true; }
1169 bool isComplexInt() const { return IsInt; }
1170 APSInt &getComplexIntReal() { return IntReal; }
1171 APSInt &getComplexIntImag() { return IntImag; }
1172
Richard Smith2e312c82012-03-03 22:46:17 +00001173 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001174 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001175 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001176 else
Richard Smith2e312c82012-03-03 22:46:17 +00001177 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001178 }
Richard Smith2e312c82012-03-03 22:46:17 +00001179 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001180 assert(v.isComplexFloat() || v.isComplexInt());
1181 if (v.isComplexFloat()) {
1182 makeComplexFloat();
1183 FloatReal = v.getComplexFloatReal();
1184 FloatImag = v.getComplexFloatImag();
1185 } else {
1186 makeComplexInt();
1187 IntReal = v.getComplexIntReal();
1188 IntImag = v.getComplexIntImag();
1189 }
1190 }
John McCall93d91dc2010-05-07 17:22:02 +00001191 };
John McCall45d55e42010-05-07 21:00:08 +00001192
1193 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001194 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001195 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001196 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001197 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001198 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001199 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001200
Richard Smithce40ad62011-11-12 22:28:03 +00001201 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001202 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001203 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001204 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001205 SubobjectDesignator &getLValueDesignator() { return Designator; }
1206 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001207 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001208
Richard Smith2e312c82012-03-03 22:46:17 +00001209 void moveInto(APValue &V) const {
1210 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001211 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1212 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001213 else {
1214 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1215 assert(!Designator.FirstEntryIsAnUnsizedArray &&
1216 "Unsized array with a valid base?");
Richard Smith2e312c82012-03-03 22:46:17 +00001217 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001218 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001219 }
John McCall45d55e42010-05-07 21:00:08 +00001220 }
Richard Smith2e312c82012-03-03 22:46:17 +00001221 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001222 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001223 Base = V.getLValueBase();
1224 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001225 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001226 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001227 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001228 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001229 }
1230
Yaxun Liu402804b2016-12-15 08:09:08 +00001231 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
1232 bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
George Burgess IVe3763372016-12-22 02:50:20 +00001233#ifndef NDEBUG
1234 // We only allow a few types of invalid bases. Enforce that here.
1235 if (BInvalid) {
1236 const auto *E = B.get<const Expr *>();
1237 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1238 "Unexpected type of invalid base");
1239 }
1240#endif
1241
Richard Smithce40ad62011-11-12 22:28:03 +00001242 Base = B;
Yaxun Liu402804b2016-12-15 08:09:08 +00001243 Offset = CharUnits::fromQuantity(Offset_);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001244 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001245 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001246 Designator = SubobjectDesignator(getType(B));
Yaxun Liu402804b2016-12-15 08:09:08 +00001247 IsNullPtr = IsNullPtr_;
Richard Smitha8105bc2012-01-06 16:39:00 +00001248 }
1249
George Burgess IV3a03fab2015-09-04 21:28:13 +00001250 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1251 set(B, I, true);
1252 }
1253
Richard Smitha8105bc2012-01-06 16:39:00 +00001254 // Check that this LValue is not based on a null pointer. If it is, produce
1255 // a diagnostic and mark the designator as invalid.
1256 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1257 CheckSubobjectKind CSK) {
1258 if (Designator.Invalid)
1259 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001260 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001261 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001262 << CSK;
1263 Designator.setInvalid();
1264 return false;
1265 }
1266 return true;
1267 }
1268
1269 // Check this LValue refers to an object. If not, set the designator to be
1270 // invalid and emit a diagnostic.
1271 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001272 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001273 Designator.checkSubobject(Info, E, CSK);
1274 }
1275
1276 void addDecl(EvalInfo &Info, const Expr *E,
1277 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001278 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1279 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001280 }
George Burgess IVe3763372016-12-22 02:50:20 +00001281 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1282 assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1283 assert(isBaseAnAllocSizeCall(Base) &&
1284 "Only alloc_size bases can have unsized arrays");
1285 Designator.FirstEntryIsAnUnsizedArray = true;
1286 Designator.addUnsizedArrayUnchecked(ElemTy);
1287 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001288 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001289 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1290 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001291 }
Richard Smith66c96992012-02-18 22:04:06 +00001292 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001293 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1294 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001295 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001296 void clearIsNullPointer() {
1297 IsNullPtr = false;
1298 }
Richard Smithd6cc1982017-01-31 02:23:02 +00001299 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, APSInt Index,
Yaxun Liu402804b2016-12-15 08:09:08 +00001300 CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001301 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1302 // but we're not required to diagnose it and it's valid in C++.)
1303 if (!Index)
1304 return;
1305
1306 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1307 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1308 // offsets.
1309 uint64_t Offset64 = Offset.getQuantity();
1310 uint64_t ElemSize64 = ElementSize.getQuantity();
1311 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1312 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1313
1314 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001315 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001316 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001317 }
1318 void adjustOffset(CharUnits N) {
1319 Offset += N;
1320 if (N.getQuantity())
1321 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001322 }
John McCall45d55e42010-05-07 21:00:08 +00001323 };
Richard Smith027bf112011-11-17 22:56:20 +00001324
1325 struct MemberPtr {
1326 MemberPtr() {}
1327 explicit MemberPtr(const ValueDecl *Decl) :
1328 DeclAndIsDerivedMember(Decl, false), Path() {}
1329
1330 /// The member or (direct or indirect) field referred to by this member
1331 /// pointer, or 0 if this is a null member pointer.
1332 const ValueDecl *getDecl() const {
1333 return DeclAndIsDerivedMember.getPointer();
1334 }
1335 /// Is this actually a member of some type derived from the relevant class?
1336 bool isDerivedMember() const {
1337 return DeclAndIsDerivedMember.getInt();
1338 }
1339 /// Get the class which the declaration actually lives in.
1340 const CXXRecordDecl *getContainingRecord() const {
1341 return cast<CXXRecordDecl>(
1342 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1343 }
1344
Richard Smith2e312c82012-03-03 22:46:17 +00001345 void moveInto(APValue &V) const {
1346 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001347 }
Richard Smith2e312c82012-03-03 22:46:17 +00001348 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001349 assert(V.isMemberPointer());
1350 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1351 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1352 Path.clear();
1353 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1354 Path.insert(Path.end(), P.begin(), P.end());
1355 }
1356
1357 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1358 /// whether the member is a member of some class derived from the class type
1359 /// of the member pointer.
1360 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1361 /// Path - The path of base/derived classes from the member declaration's
1362 /// class (exclusive) to the class type of the member pointer (inclusive).
1363 SmallVector<const CXXRecordDecl*, 4> Path;
1364
1365 /// Perform a cast towards the class of the Decl (either up or down the
1366 /// hierarchy).
1367 bool castBack(const CXXRecordDecl *Class) {
1368 assert(!Path.empty());
1369 const CXXRecordDecl *Expected;
1370 if (Path.size() >= 2)
1371 Expected = Path[Path.size() - 2];
1372 else
1373 Expected = getContainingRecord();
1374 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1375 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1376 // if B does not contain the original member and is not a base or
1377 // derived class of the class containing the original member, the result
1378 // of the cast is undefined.
1379 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1380 // (D::*). We consider that to be a language defect.
1381 return false;
1382 }
1383 Path.pop_back();
1384 return true;
1385 }
1386 /// Perform a base-to-derived member pointer cast.
1387 bool castToDerived(const CXXRecordDecl *Derived) {
1388 if (!getDecl())
1389 return true;
1390 if (!isDerivedMember()) {
1391 Path.push_back(Derived);
1392 return true;
1393 }
1394 if (!castBack(Derived))
1395 return false;
1396 if (Path.empty())
1397 DeclAndIsDerivedMember.setInt(false);
1398 return true;
1399 }
1400 /// Perform a derived-to-base member pointer cast.
1401 bool castToBase(const CXXRecordDecl *Base) {
1402 if (!getDecl())
1403 return true;
1404 if (Path.empty())
1405 DeclAndIsDerivedMember.setInt(true);
1406 if (isDerivedMember()) {
1407 Path.push_back(Base);
1408 return true;
1409 }
1410 return castBack(Base);
1411 }
1412 };
Richard Smith357362d2011-12-13 06:39:58 +00001413
Richard Smith7bb00672012-02-01 01:42:44 +00001414 /// Compare two member pointers, which are assumed to be of the same type.
1415 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1416 if (!LHS.getDecl() || !RHS.getDecl())
1417 return !LHS.getDecl() && !RHS.getDecl();
1418 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1419 return false;
1420 return LHS.Path == RHS.Path;
1421 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001422}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001423
Richard Smith2e312c82012-03-03 22:46:17 +00001424static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001425static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1426 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001427 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001428static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1429 bool InvalidBaseOK = false);
1430static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1431 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001432static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1433 EvalInfo &Info);
1434static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001435static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001436static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001437 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001438static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001439static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001440static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001441static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001442
1443//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001444// Misc utilities
1445//===----------------------------------------------------------------------===//
1446
Richard Smithd6cc1982017-01-31 02:23:02 +00001447/// Negate an APSInt in place, converting it to a signed form if necessary, and
1448/// preserving its value (by extending by up to one bit as needed).
1449static void negateAsSigned(APSInt &Int) {
1450 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1451 Int = Int.extend(Int.getBitWidth() + 1);
1452 Int.setIsSigned(true);
1453 }
1454 Int = -Int;
1455}
1456
Richard Smith84401042013-06-03 05:03:02 +00001457/// Produce a string describing the given constexpr call.
1458static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1459 unsigned ArgIndex = 0;
1460 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1461 !isa<CXXConstructorDecl>(Frame->Callee) &&
1462 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1463
1464 if (!IsMemberCall)
1465 Out << *Frame->Callee << '(';
1466
1467 if (Frame->This && IsMemberCall) {
1468 APValue Val;
1469 Frame->This->moveInto(Val);
1470 Val.printPretty(Out, Frame->Info.Ctx,
1471 Frame->This->Designator.MostDerivedType);
1472 // FIXME: Add parens around Val if needed.
1473 Out << "->" << *Frame->Callee << '(';
1474 IsMemberCall = false;
1475 }
1476
1477 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1478 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1479 if (ArgIndex > (unsigned)IsMemberCall)
1480 Out << ", ";
1481
1482 const ParmVarDecl *Param = *I;
1483 const APValue &Arg = Frame->Arguments[ArgIndex];
1484 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1485
1486 if (ArgIndex == 0 && IsMemberCall)
1487 Out << "->" << *Frame->Callee << '(';
1488 }
1489
1490 Out << ')';
1491}
1492
Richard Smithd9f663b2013-04-22 15:31:51 +00001493/// Evaluate an expression to see if it had side-effects, and discard its
1494/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001495/// \return \c true if the caller should keep evaluating.
1496static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001497 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001498 if (!Evaluate(Scratch, Info, E))
1499 // We don't need the value, but we might have skipped a side effect here.
1500 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001501 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001502}
1503
Richard Smithd62306a2011-11-10 06:34:14 +00001504/// Should this call expression be treated as a string literal?
1505static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001506 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001507 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1508 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1509}
1510
Richard Smithce40ad62011-11-12 22:28:03 +00001511static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001512 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1513 // constant expression of pointer type that evaluates to...
1514
1515 // ... a null pointer value, or a prvalue core constant expression of type
1516 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001517 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001518
Richard Smithce40ad62011-11-12 22:28:03 +00001519 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1520 // ... the address of an object with static storage duration,
1521 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1522 return VD->hasGlobalStorage();
1523 // ... the address of a function,
1524 return isa<FunctionDecl>(D);
1525 }
1526
1527 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001528 switch (E->getStmtClass()) {
1529 default:
1530 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001531 case Expr::CompoundLiteralExprClass: {
1532 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1533 return CLE->isFileScope() && CLE->isLValue();
1534 }
Richard Smithe6c01442013-06-05 00:46:14 +00001535 case Expr::MaterializeTemporaryExprClass:
1536 // A materialized temporary might have been lifetime-extended to static
1537 // storage duration.
1538 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001539 // A string literal has static storage duration.
1540 case Expr::StringLiteralClass:
1541 case Expr::PredefinedExprClass:
1542 case Expr::ObjCStringLiteralClass:
1543 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001544 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001545 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001546 return true;
1547 case Expr::CallExprClass:
1548 return IsStringLiteralCall(cast<CallExpr>(E));
1549 // For GCC compatibility, &&label has static storage duration.
1550 case Expr::AddrLabelExprClass:
1551 return true;
1552 // A Block literal expression may be used as the initialization value for
1553 // Block variables at global or local static scope.
1554 case Expr::BlockExprClass:
1555 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001556 case Expr::ImplicitValueInitExprClass:
1557 // FIXME:
1558 // We can never form an lvalue with an implicit value initialization as its
1559 // base through expression evaluation, so these only appear in one case: the
1560 // implicit variable declaration we invent when checking whether a constexpr
1561 // constructor can produce a constant expression. We must assume that such
1562 // an expression might be a global lvalue.
1563 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001564 }
John McCall95007602010-05-10 23:27:23 +00001565}
1566
Richard Smithb228a862012-02-15 02:18:13 +00001567static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1568 assert(Base && "no location for a null lvalue");
1569 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1570 if (VD)
1571 Info.Note(VD->getLocation(), diag::note_declared_at);
1572 else
Ted Kremenek28831752012-08-23 20:46:57 +00001573 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001574 diag::note_constexpr_temporary_here);
1575}
1576
Richard Smith80815602011-11-07 05:07:52 +00001577/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001578/// value for an address or reference constant expression. Return true if we
1579/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001580static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1581 QualType Type, const LValue &LVal) {
1582 bool IsReferenceType = Type->isReferenceType();
1583
Richard Smith357362d2011-12-13 06:39:58 +00001584 APValue::LValueBase Base = LVal.getLValueBase();
1585 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1586
Richard Smith0dea49e2012-02-18 04:58:18 +00001587 // Check that the object is a global. Note that the fake 'this' object we
1588 // manufacture when checking potential constant expressions is conservatively
1589 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001590 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001591 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001592 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001593 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001594 << IsReferenceType << !Designator.Entries.empty()
1595 << !!VD << VD;
1596 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001597 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001598 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001599 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001600 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001601 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001602 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001603 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001604 LVal.getLValueCallIndex() == 0) &&
1605 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001606
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001607 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1608 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001609 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001610 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001611 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001612
Hans Wennborg82dd8772014-06-25 22:19:48 +00001613 // A dllimport variable never acts like a constant.
1614 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001615 return false;
1616 }
1617 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1618 // __declspec(dllimport) must be handled very carefully:
1619 // We must never initialize an expression with the thunk in C++.
1620 // Doing otherwise would allow the same id-expression to yield
1621 // different addresses for the same function in different translation
1622 // units. However, this means that we must dynamically initialize the
1623 // expression with the contents of the import address table at runtime.
1624 //
1625 // The C language has no notion of ODR; furthermore, it has no notion of
1626 // dynamic initialization. This means that we are permitted to
1627 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001628 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001629 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001630 }
1631 }
1632
Richard Smitha8105bc2012-01-06 16:39:00 +00001633 // Allow address constant expressions to be past-the-end pointers. This is
1634 // an extension: the standard requires them to point to an object.
1635 if (!IsReferenceType)
1636 return true;
1637
1638 // A reference constant expression must refer to an object.
1639 if (!Base) {
1640 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001641 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001642 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001643 }
1644
Richard Smith357362d2011-12-13 06:39:58 +00001645 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001646 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001647 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001648 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001649 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001650 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001651 }
1652
Richard Smith80815602011-11-07 05:07:52 +00001653 return true;
1654}
1655
Richard Smithfddd3842011-12-30 21:15:51 +00001656/// Check that this core constant expression is of literal type, and if not,
1657/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001658static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001659 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001660 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001661 return true;
1662
Richard Smith7525ff62013-05-09 07:14:00 +00001663 // C++1y: A constant initializer for an object o [...] may also invoke
1664 // constexpr constructors for o and its subobjects even if those objects
1665 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001666 //
1667 // C++11 missed this detail for aggregates, so classes like this:
1668 // struct foo_t { union { int i; volatile int j; } u; };
1669 // are not (obviously) initializable like so:
1670 // __attribute__((__require_constant_initialization__))
1671 // static const foo_t x = {{0}};
1672 // because "i" is a subobject with non-literal initialization (due to the
1673 // volatile member of the union). See:
1674 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1675 // Therefore, we use the C++1y behavior.
1676 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001677 return true;
1678
Richard Smithfddd3842011-12-30 21:15:51 +00001679 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001680 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001681 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001682 << E->getType();
1683 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001684 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001685 return false;
1686}
1687
Richard Smith0b0a0b62011-10-29 20:57:55 +00001688/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001689/// constant expression. If not, report an appropriate diagnostic. Does not
1690/// check that the expression is of literal type.
1691static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1692 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001693 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001694 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001695 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001696 return false;
1697 }
1698
Richard Smith77be48a2014-07-31 06:31:19 +00001699 // We allow _Atomic(T) to be initialized from anything that T can be
1700 // initialized from.
1701 if (const AtomicType *AT = Type->getAs<AtomicType>())
1702 Type = AT->getValueType();
1703
Richard Smithb228a862012-02-15 02:18:13 +00001704 // Core issue 1454: For a literal constant expression of array or class type,
1705 // each subobject of its value shall have been initialized by a constant
1706 // expression.
1707 if (Value.isArray()) {
1708 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1709 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1710 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1711 Value.getArrayInitializedElt(I)))
1712 return false;
1713 }
1714 if (!Value.hasArrayFiller())
1715 return true;
1716 return CheckConstantExpression(Info, DiagLoc, EltTy,
1717 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001718 }
Richard Smithb228a862012-02-15 02:18:13 +00001719 if (Value.isUnion() && Value.getUnionField()) {
1720 return CheckConstantExpression(Info, DiagLoc,
1721 Value.getUnionField()->getType(),
1722 Value.getUnionValue());
1723 }
1724 if (Value.isStruct()) {
1725 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1726 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1727 unsigned BaseIndex = 0;
1728 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1729 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1730 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1731 Value.getStructBase(BaseIndex)))
1732 return false;
1733 }
1734 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001735 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001736 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1737 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001738 return false;
1739 }
1740 }
1741
1742 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001743 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001744 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001745 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1746 }
1747
1748 // Everything else is fine.
1749 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001750}
1751
Benjamin Kramer8407df72015-03-09 16:47:52 +00001752static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001753 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001754}
1755
1756static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001757 if (Value.CallIndex)
1758 return false;
1759 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1760 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001761}
1762
Richard Smithcecf1842011-11-01 21:06:14 +00001763static bool IsWeakLValue(const LValue &Value) {
1764 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001765 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001766}
1767
David Majnemerb5116032014-12-09 23:32:34 +00001768static bool isZeroSized(const LValue &Value) {
1769 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001770 if (Decl && isa<VarDecl>(Decl)) {
1771 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001772 if (Ty->isArrayType())
1773 return Ty->isIncompleteType() ||
1774 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001775 }
1776 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001777}
1778
Richard Smith2e312c82012-03-03 22:46:17 +00001779static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001780 // A null base expression indicates a null pointer. These are always
1781 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001782 if (!Value.getLValueBase()) {
1783 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001784 return true;
1785 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001786
Richard Smith027bf112011-11-17 22:56:20 +00001787 // We have a non-null base. These are generally known to be true, but if it's
1788 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001789 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001790 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001791 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001792}
1793
Richard Smith2e312c82012-03-03 22:46:17 +00001794static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001795 switch (Val.getKind()) {
1796 case APValue::Uninitialized:
1797 return false;
1798 case APValue::Int:
1799 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001800 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001801 case APValue::Float:
1802 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001803 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001804 case APValue::ComplexInt:
1805 Result = Val.getComplexIntReal().getBoolValue() ||
1806 Val.getComplexIntImag().getBoolValue();
1807 return true;
1808 case APValue::ComplexFloat:
1809 Result = !Val.getComplexFloatReal().isZero() ||
1810 !Val.getComplexFloatImag().isZero();
1811 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001812 case APValue::LValue:
1813 return EvalPointerValueAsBool(Val, Result);
1814 case APValue::MemberPointer:
1815 Result = Val.getMemberPointerDecl();
1816 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001817 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001818 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001819 case APValue::Struct:
1820 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001821 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001822 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001823 }
1824
Richard Smith11562c52011-10-28 17:51:58 +00001825 llvm_unreachable("unknown APValue kind");
1826}
1827
1828static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1829 EvalInfo &Info) {
1830 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001831 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001832 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001833 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001834 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001835}
1836
Richard Smith357362d2011-12-13 06:39:58 +00001837template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001838static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001839 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001840 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001841 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001842 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001843}
1844
1845static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1846 QualType SrcType, const APFloat &Value,
1847 QualType DestType, APSInt &Result) {
1848 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001849 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001850 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001851
Richard Smith357362d2011-12-13 06:39:58 +00001852 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001853 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001854 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1855 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001856 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001857 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001858}
1859
Richard Smith357362d2011-12-13 06:39:58 +00001860static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1861 QualType SrcType, QualType DestType,
1862 APFloat &Result) {
1863 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001864 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001865 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1866 APFloat::rmNearestTiesToEven, &ignored)
1867 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001868 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001869 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001870}
1871
Richard Smith911e1422012-01-30 22:27:01 +00001872static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1873 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001874 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001875 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001876 APSInt Result = Value;
1877 // Figure out if this is a truncate, extend or noop cast.
1878 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001879 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001880 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001881 return Result;
1882}
1883
Richard Smith357362d2011-12-13 06:39:58 +00001884static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1885 QualType SrcType, const APSInt &Value,
1886 QualType DestType, APFloat &Result) {
1887 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1888 if (Result.convertFromAPInt(Value, Value.isSigned(),
1889 APFloat::rmNearestTiesToEven)
1890 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001891 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001892 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001893}
1894
Richard Smith49ca8aa2013-08-06 07:09:20 +00001895static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1896 APValue &Value, const FieldDecl *FD) {
1897 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1898
1899 if (!Value.isInt()) {
1900 // Trying to store a pointer-cast-to-integer into a bitfield.
1901 // FIXME: In this case, we should provide the diagnostic for casting
1902 // a pointer to an integer.
1903 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001904 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001905 return false;
1906 }
1907
1908 APSInt &Int = Value.getInt();
1909 unsigned OldBitWidth = Int.getBitWidth();
1910 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1911 if (NewBitWidth < OldBitWidth)
1912 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1913 return true;
1914}
1915
Eli Friedman803acb32011-12-22 03:51:45 +00001916static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1917 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001918 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001919 if (!Evaluate(SVal, Info, E))
1920 return false;
1921 if (SVal.isInt()) {
1922 Res = SVal.getInt();
1923 return true;
1924 }
1925 if (SVal.isFloat()) {
1926 Res = SVal.getFloat().bitcastToAPInt();
1927 return true;
1928 }
1929 if (SVal.isVector()) {
1930 QualType VecTy = E->getType();
1931 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1932 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1933 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1934 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1935 Res = llvm::APInt::getNullValue(VecSize);
1936 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1937 APValue &Elt = SVal.getVectorElt(i);
1938 llvm::APInt EltAsInt;
1939 if (Elt.isInt()) {
1940 EltAsInt = Elt.getInt();
1941 } else if (Elt.isFloat()) {
1942 EltAsInt = Elt.getFloat().bitcastToAPInt();
1943 } else {
1944 // Don't try to handle vectors of anything other than int or float
1945 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001946 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001947 return false;
1948 }
1949 unsigned BaseEltSize = EltAsInt.getBitWidth();
1950 if (BigEndian)
1951 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1952 else
1953 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1954 }
1955 return true;
1956 }
1957 // Give up if the input isn't an int, float, or vector. For example, we
1958 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001959 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001960 return false;
1961}
1962
Richard Smith43e77732013-05-07 04:50:00 +00001963/// Perform the given integer operation, which is known to need at most BitWidth
1964/// bits, and check for overflow in the original type (if that type was not an
1965/// unsigned type).
1966template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001967static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1968 const APSInt &LHS, const APSInt &RHS,
1969 unsigned BitWidth, Operation Op,
1970 APSInt &Result) {
1971 if (LHS.isUnsigned()) {
1972 Result = Op(LHS, RHS);
1973 return true;
1974 }
Richard Smith43e77732013-05-07 04:50:00 +00001975
1976 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001977 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001978 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001979 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001980 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001981 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001982 << Result.toString(10) << E->getType();
1983 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001984 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001985 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001986 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001987}
1988
1989/// Perform the given binary integer operation.
1990static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1991 BinaryOperatorKind Opcode, APSInt RHS,
1992 APSInt &Result) {
1993 switch (Opcode) {
1994 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001995 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00001996 return false;
1997 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001998 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1999 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002000 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002001 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2002 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002003 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002004 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2005 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002006 case BO_And: Result = LHS & RHS; return true;
2007 case BO_Xor: Result = LHS ^ RHS; return true;
2008 case BO_Or: Result = LHS | RHS; return true;
2009 case BO_Div:
2010 case BO_Rem:
2011 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002012 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002013 return false;
2014 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002015 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2016 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2017 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002018 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2019 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002020 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2021 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002022 return true;
2023 case BO_Shl: {
2024 if (Info.getLangOpts().OpenCL)
2025 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2026 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2027 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2028 RHS.isUnsigned());
2029 else if (RHS.isSigned() && RHS.isNegative()) {
2030 // During constant-folding, a negative shift is an opposite shift. Such
2031 // a shift is not a constant expression.
2032 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2033 RHS = -RHS;
2034 goto shift_right;
2035 }
2036 shift_left:
2037 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2038 // the shifted type.
2039 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2040 if (SA != RHS) {
2041 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2042 << RHS << E->getType() << LHS.getBitWidth();
2043 } else if (LHS.isSigned()) {
2044 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2045 // operand, and must not overflow the corresponding unsigned type.
2046 if (LHS.isNegative())
2047 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2048 else if (LHS.countLeadingZeros() < SA)
2049 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2050 }
2051 Result = LHS << SA;
2052 return true;
2053 }
2054 case BO_Shr: {
2055 if (Info.getLangOpts().OpenCL)
2056 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2057 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2058 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2059 RHS.isUnsigned());
2060 else if (RHS.isSigned() && RHS.isNegative()) {
2061 // During constant-folding, a negative shift is an opposite shift. Such a
2062 // shift is not a constant expression.
2063 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2064 RHS = -RHS;
2065 goto shift_left;
2066 }
2067 shift_right:
2068 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2069 // shifted type.
2070 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2071 if (SA != RHS)
2072 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2073 << RHS << E->getType() << LHS.getBitWidth();
2074 Result = LHS >> SA;
2075 return true;
2076 }
2077
2078 case BO_LT: Result = LHS < RHS; return true;
2079 case BO_GT: Result = LHS > RHS; return true;
2080 case BO_LE: Result = LHS <= RHS; return true;
2081 case BO_GE: Result = LHS >= RHS; return true;
2082 case BO_EQ: Result = LHS == RHS; return true;
2083 case BO_NE: Result = LHS != RHS; return true;
2084 }
2085}
2086
Richard Smith861b5b52013-05-07 23:34:45 +00002087/// Perform the given binary floating-point operation, in-place, on LHS.
2088static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2089 APFloat &LHS, BinaryOperatorKind Opcode,
2090 const APFloat &RHS) {
2091 switch (Opcode) {
2092 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002093 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002094 return false;
2095 case BO_Mul:
2096 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2097 break;
2098 case BO_Add:
2099 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2100 break;
2101 case BO_Sub:
2102 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2103 break;
2104 case BO_Div:
2105 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2106 break;
2107 }
2108
Richard Smith0c6124b2015-12-03 01:36:22 +00002109 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002110 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002111 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002112 }
Richard Smith861b5b52013-05-07 23:34:45 +00002113 return true;
2114}
2115
Richard Smitha8105bc2012-01-06 16:39:00 +00002116/// Cast an lvalue referring to a base subobject to a derived class, by
2117/// truncating the lvalue's path to the given length.
2118static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2119 const RecordDecl *TruncatedType,
2120 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002121 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002122
2123 // Check we actually point to a derived class object.
2124 if (TruncatedElements == D.Entries.size())
2125 return true;
2126 assert(TruncatedElements >= D.MostDerivedPathLength &&
2127 "not casting to a derived class");
2128 if (!Result.checkSubobject(Info, E, CSK_Derived))
2129 return false;
2130
2131 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002132 const RecordDecl *RD = TruncatedType;
2133 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002134 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002135 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2136 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002137 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002138 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002139 else
Richard Smithd62306a2011-11-10 06:34:14 +00002140 Result.Offset -= Layout.getBaseClassOffset(Base);
2141 RD = Base;
2142 }
Richard Smith027bf112011-11-17 22:56:20 +00002143 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002144 return true;
2145}
2146
John McCalld7bca762012-05-01 00:38:49 +00002147static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002148 const CXXRecordDecl *Derived,
2149 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002150 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002151 if (!RL) {
2152 if (Derived->isInvalidDecl()) return false;
2153 RL = &Info.Ctx.getASTRecordLayout(Derived);
2154 }
2155
Richard Smithd62306a2011-11-10 06:34:14 +00002156 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002157 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002158 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002159}
2160
Richard Smitha8105bc2012-01-06 16:39:00 +00002161static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002162 const CXXRecordDecl *DerivedDecl,
2163 const CXXBaseSpecifier *Base) {
2164 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2165
John McCalld7bca762012-05-01 00:38:49 +00002166 if (!Base->isVirtual())
2167 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002168
Richard Smitha8105bc2012-01-06 16:39:00 +00002169 SubobjectDesignator &D = Obj.Designator;
2170 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002171 return false;
2172
Richard Smitha8105bc2012-01-06 16:39:00 +00002173 // Extract most-derived object and corresponding type.
2174 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2175 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2176 return false;
2177
2178 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002179 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002180 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2181 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002182 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002183 return true;
2184}
2185
Richard Smith84401042013-06-03 05:03:02 +00002186static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2187 QualType Type, LValue &Result) {
2188 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2189 PathE = E->path_end();
2190 PathI != PathE; ++PathI) {
2191 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2192 *PathI))
2193 return false;
2194 Type = (*PathI)->getType();
2195 }
2196 return true;
2197}
2198
Richard Smithd62306a2011-11-10 06:34:14 +00002199/// Update LVal to refer to the given field, which must be a member of the type
2200/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002201static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002202 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002203 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002204 if (!RL) {
2205 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002206 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002207 }
Richard Smithd62306a2011-11-10 06:34:14 +00002208
2209 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002210 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002211 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002212 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002213}
2214
Richard Smith1b78b3d2012-01-25 22:15:11 +00002215/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002216static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002217 LValue &LVal,
2218 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002219 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002220 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002221 return false;
2222 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002223}
2224
Richard Smithd62306a2011-11-10 06:34:14 +00002225/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002226static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2227 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002228 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2229 // extension.
2230 if (Type->isVoidType() || Type->isFunctionType()) {
2231 Size = CharUnits::One();
2232 return true;
2233 }
2234
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002235 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002236 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002237 return false;
2238 }
2239
Richard Smithd62306a2011-11-10 06:34:14 +00002240 if (!Type->isConstantSizeType()) {
2241 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002242 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002243 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002244 return false;
2245 }
2246
2247 Size = Info.Ctx.getTypeSizeInChars(Type);
2248 return true;
2249}
2250
2251/// Update a pointer value to model pointer arithmetic.
2252/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002253/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002254/// \param LVal - The pointer value to be updated.
2255/// \param EltTy - The pointee type represented by LVal.
2256/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002257static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2258 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002259 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002260 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002261 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002262 return false;
2263
Yaxun Liu402804b2016-12-15 08:09:08 +00002264 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002265 return true;
2266}
2267
Richard Smithd6cc1982017-01-31 02:23:02 +00002268static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2269 LValue &LVal, QualType EltTy,
2270 int64_t Adjustment) {
2271 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2272 APSInt::get(Adjustment));
2273}
2274
Richard Smith66c96992012-02-18 22:04:06 +00002275/// Update an lvalue to refer to a component of a complex number.
2276/// \param Info - Information about the ongoing evaluation.
2277/// \param LVal - The lvalue to be updated.
2278/// \param EltTy - The complex number's component type.
2279/// \param Imag - False for the real component, true for the imaginary.
2280static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2281 LValue &LVal, QualType EltTy,
2282 bool Imag) {
2283 if (Imag) {
2284 CharUnits SizeOfComponent;
2285 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2286 return false;
2287 LVal.Offset += SizeOfComponent;
2288 }
2289 LVal.addComplex(Info, E, EltTy, Imag);
2290 return true;
2291}
2292
Faisal Vali051e3a22017-02-16 04:12:21 +00002293static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2294 QualType Type, const LValue &LVal,
2295 APValue &RVal);
2296
Richard Smith27908702011-10-24 17:54:18 +00002297/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002298///
2299/// \param Info Information about the ongoing evaluation.
2300/// \param E An expression to be used when printing diagnostics.
2301/// \param VD The variable whose initializer should be obtained.
2302/// \param Frame The frame in which the variable was created. Must be null
2303/// if this variable is not local to the evaluation.
2304/// \param Result Filled in with a pointer to the value of the variable.
2305static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2306 const VarDecl *VD, CallStackFrame *Frame,
2307 APValue *&Result) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002308
Richard Smith254a73d2011-10-28 22:34:42 +00002309 // If this is a parameter to an active constexpr function call, perform
2310 // argument substitution.
2311 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002312 // Assume arguments of a potential constant expression are unknown
2313 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002314 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002315 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002316 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002317 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002318 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002319 }
Richard Smith3229b742013-05-05 21:17:10 +00002320 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002321 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002322 }
Richard Smith27908702011-10-24 17:54:18 +00002323
Richard Smithd9f663b2013-04-22 15:31:51 +00002324 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002325 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002326 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002327 if (!Result) {
2328 // Assume variables referenced within a lambda's call operator that were
2329 // not declared within the call operator are captures and during checking
2330 // of a potential constant expression, assume they are unknown constant
2331 // expressions.
2332 assert(isLambdaCallOperator(Frame->Callee) &&
2333 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2334 "missing value for local variable");
2335 if (Info.checkingPotentialConstantExpression())
2336 return false;
2337 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002338 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002339 diag::note_unimplemented_constexpr_lambda_feature_ast)
2340 << "captures not currently allowed";
2341 return false;
2342 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002343 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002344 }
2345
Richard Smithd0b4dd62011-12-19 06:19:21 +00002346 // Dig out the initializer, and use the declaration which it's attached to.
2347 const Expr *Init = VD->getAnyInitializer(VD);
2348 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002349 // If we're checking a potential constant expression, the variable could be
2350 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002351 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002352 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002353 return false;
2354 }
2355
Richard Smithd62306a2011-11-10 06:34:14 +00002356 // If we're currently evaluating the initializer of this declaration, use that
2357 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002358 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002359 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002360 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002361 }
2362
Richard Smithcecf1842011-11-01 21:06:14 +00002363 // Never evaluate the initializer of a weak variable. We can't be sure that
2364 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002365 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002366 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002367 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002368 }
Richard Smithcecf1842011-11-01 21:06:14 +00002369
Richard Smithd0b4dd62011-12-19 06:19:21 +00002370 // Check that we can fold the initializer. In C++, we will have already done
2371 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002372 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002373 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002374 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002375 Notes.size() + 1) << VD;
2376 Info.Note(VD->getLocation(), diag::note_declared_at);
2377 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002378 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002379 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002380 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002381 Notes.size() + 1) << VD;
2382 Info.Note(VD->getLocation(), diag::note_declared_at);
2383 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002384 }
Richard Smith27908702011-10-24 17:54:18 +00002385
Richard Smith3229b742013-05-05 21:17:10 +00002386 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002387 return true;
Richard Smith27908702011-10-24 17:54:18 +00002388}
2389
Richard Smith11562c52011-10-28 17:51:58 +00002390static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002391 Qualifiers Quals = T.getQualifiers();
2392 return Quals.hasConst() && !Quals.hasVolatile();
2393}
2394
Richard Smithe97cbd72011-11-11 04:05:33 +00002395/// Get the base index of the given base class within an APValue representing
2396/// the given derived class.
2397static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2398 const CXXRecordDecl *Base) {
2399 Base = Base->getCanonicalDecl();
2400 unsigned Index = 0;
2401 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2402 E = Derived->bases_end(); I != E; ++I, ++Index) {
2403 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2404 return Index;
2405 }
2406
2407 llvm_unreachable("base class missing from derived class's bases list");
2408}
2409
Richard Smith3da88fa2013-04-26 14:36:30 +00002410/// Extract the value of a character from a string literal.
2411static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2412 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002413 // FIXME: Support MakeStringConstant
2414 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2415 std::string Str;
2416 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2417 assert(Index <= Str.size() && "Index too large");
2418 return APSInt::getUnsigned(Str.c_str()[Index]);
2419 }
2420
Alexey Bataevec474782014-10-09 08:45:04 +00002421 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2422 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002423 const StringLiteral *S = cast<StringLiteral>(Lit);
2424 const ConstantArrayType *CAT =
2425 Info.Ctx.getAsConstantArrayType(S->getType());
2426 assert(CAT && "string literal isn't an array");
2427 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002428 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002429
2430 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002431 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002432 if (Index < S->getLength())
2433 Value = S->getCodeUnit(Index);
2434 return Value;
2435}
2436
Richard Smith3da88fa2013-04-26 14:36:30 +00002437// Expand a string literal into an array of characters.
2438static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2439 APValue &Result) {
2440 const StringLiteral *S = cast<StringLiteral>(Lit);
2441 const ConstantArrayType *CAT =
2442 Info.Ctx.getAsConstantArrayType(S->getType());
2443 assert(CAT && "string literal isn't an array");
2444 QualType CharType = CAT->getElementType();
2445 assert(CharType->isIntegerType() && "unexpected character type");
2446
2447 unsigned Elts = CAT->getSize().getZExtValue();
2448 Result = APValue(APValue::UninitArray(),
2449 std::min(S->getLength(), Elts), Elts);
2450 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2451 CharType->isUnsignedIntegerType());
2452 if (Result.hasArrayFiller())
2453 Result.getArrayFiller() = APValue(Value);
2454 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2455 Value = S->getCodeUnit(I);
2456 Result.getArrayInitializedElt(I) = APValue(Value);
2457 }
2458}
2459
2460// Expand an array so that it has more than Index filled elements.
2461static void expandArray(APValue &Array, unsigned Index) {
2462 unsigned Size = Array.getArraySize();
2463 assert(Index < Size);
2464
2465 // Always at least double the number of elements for which we store a value.
2466 unsigned OldElts = Array.getArrayInitializedElts();
2467 unsigned NewElts = std::max(Index+1, OldElts * 2);
2468 NewElts = std::min(Size, std::max(NewElts, 8u));
2469
2470 // Copy the data across.
2471 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2472 for (unsigned I = 0; I != OldElts; ++I)
2473 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2474 for (unsigned I = OldElts; I != NewElts; ++I)
2475 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2476 if (NewValue.hasArrayFiller())
2477 NewValue.getArrayFiller() = Array.getArrayFiller();
2478 Array.swap(NewValue);
2479}
2480
Richard Smithb01fe402014-09-16 01:24:02 +00002481/// Determine whether a type would actually be read by an lvalue-to-rvalue
2482/// conversion. If it's of class type, we may assume that the copy operation
2483/// is trivial. Note that this is never true for a union type with fields
2484/// (because the copy always "reads" the active member) and always true for
2485/// a non-class type.
2486static bool isReadByLvalueToRvalueConversion(QualType T) {
2487 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2488 if (!RD || (RD->isUnion() && !RD->field_empty()))
2489 return true;
2490 if (RD->isEmpty())
2491 return false;
2492
2493 for (auto *Field : RD->fields())
2494 if (isReadByLvalueToRvalueConversion(Field->getType()))
2495 return true;
2496
2497 for (auto &BaseSpec : RD->bases())
2498 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2499 return true;
2500
2501 return false;
2502}
2503
2504/// Diagnose an attempt to read from any unreadable field within the specified
2505/// type, which might be a class type.
2506static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2507 QualType T) {
2508 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2509 if (!RD)
2510 return false;
2511
2512 if (!RD->hasMutableFields())
2513 return false;
2514
2515 for (auto *Field : RD->fields()) {
2516 // If we're actually going to read this field in some way, then it can't
2517 // be mutable. If we're in a union, then assigning to a mutable field
2518 // (even an empty one) can change the active member, so that's not OK.
2519 // FIXME: Add core issue number for the union case.
2520 if (Field->isMutable() &&
2521 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002522 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002523 Info.Note(Field->getLocation(), diag::note_declared_at);
2524 return true;
2525 }
2526
2527 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2528 return true;
2529 }
2530
2531 for (auto &BaseSpec : RD->bases())
2532 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2533 return true;
2534
2535 // All mutable fields were empty, and thus not actually read.
2536 return false;
2537}
2538
Richard Smith861b5b52013-05-07 23:34:45 +00002539/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002540enum AccessKinds {
2541 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002542 AK_Assign,
2543 AK_Increment,
2544 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002545};
2546
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002547namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002548/// A handle to a complete object (an object that is not a subobject of
2549/// another object).
2550struct CompleteObject {
2551 /// The value of the complete object.
2552 APValue *Value;
2553 /// The type of the complete object.
2554 QualType Type;
2555
Craig Topper36250ad2014-05-12 05:36:57 +00002556 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002557 CompleteObject(APValue *Value, QualType Type)
2558 : Value(Value), Type(Type) {
2559 assert(Value && "missing value for complete object");
2560 }
2561
Aaron Ballman67347662015-02-15 22:00:28 +00002562 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002563};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002564} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002565
Richard Smith3da88fa2013-04-26 14:36:30 +00002566/// Find the designated sub-object of an rvalue.
2567template<typename SubobjectHandler>
2568typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002569findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002570 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002571 if (Sub.Invalid)
2572 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002573 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002574 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002575 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002576 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002577 << handler.AccessKind;
2578 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002579 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002580 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002581 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002582
Richard Smith3229b742013-05-05 21:17:10 +00002583 APValue *O = Obj.Value;
2584 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002585 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002586
Richard Smithd62306a2011-11-10 06:34:14 +00002587 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002588 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2589 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002590 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002591 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002592 return handler.failed();
2593 }
2594
Richard Smith49ca8aa2013-08-06 07:09:20 +00002595 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002596 // If we are reading an object of class type, there may still be more
2597 // things we need to check: if there are any mutable subobjects, we
2598 // cannot perform this read. (This only happens when performing a trivial
2599 // copy or assignment.)
2600 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2601 diagnoseUnreadableFields(Info, E, ObjType))
2602 return handler.failed();
2603
Richard Smith49ca8aa2013-08-06 07:09:20 +00002604 if (!handler.found(*O, ObjType))
2605 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002606
Richard Smith49ca8aa2013-08-06 07:09:20 +00002607 // If we modified a bit-field, truncate it to the right width.
2608 if (handler.AccessKind != AK_Read &&
2609 LastField && LastField->isBitField() &&
2610 !truncateBitfieldValue(Info, E, *O, LastField))
2611 return false;
2612
2613 return true;
2614 }
2615
Craig Topper36250ad2014-05-12 05:36:57 +00002616 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002617 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002618 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002619 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002620 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002621 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002622 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002623 // Note, it should not be possible to form a pointer with a valid
2624 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002625 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002626 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002627 << handler.AccessKind;
2628 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002629 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002630 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002631 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002632
2633 ObjType = CAT->getElementType();
2634
Richard Smith14a94132012-02-17 03:35:37 +00002635 // An array object is represented as either an Array APValue or as an
2636 // LValue which refers to a string literal.
2637 if (O->isLValue()) {
2638 assert(I == N - 1 && "extracting subobject of character?");
2639 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002640 if (handler.AccessKind != AK_Read)
2641 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2642 *O);
2643 else
2644 return handler.foundString(*O, ObjType, Index);
2645 }
2646
2647 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002648 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002649 else if (handler.AccessKind != AK_Read) {
2650 expandArray(*O, Index);
2651 O = &O->getArrayInitializedElt(Index);
2652 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002653 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002654 } else if (ObjType->isAnyComplexType()) {
2655 // Next subobject is a complex number.
2656 uint64_t Index = Sub.Entries[I].ArrayIndex;
2657 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002658 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002659 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002660 << handler.AccessKind;
2661 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002662 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002663 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002664 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002665
2666 bool WasConstQualified = ObjType.isConstQualified();
2667 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2668 if (WasConstQualified)
2669 ObjType.addConst();
2670
Richard Smith66c96992012-02-18 22:04:06 +00002671 assert(I == N - 1 && "extracting subobject of scalar?");
2672 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002673 return handler.found(Index ? O->getComplexIntImag()
2674 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002675 } else {
2676 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002677 return handler.found(Index ? O->getComplexFloatImag()
2678 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002679 }
Richard Smithd62306a2011-11-10 06:34:14 +00002680 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002681 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002682 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002683 << Field;
2684 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002685 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002686 }
2687
Richard Smithd62306a2011-11-10 06:34:14 +00002688 // Next subobject is a class, struct or union field.
2689 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2690 if (RD->isUnion()) {
2691 const FieldDecl *UnionField = O->getUnionField();
2692 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002693 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002694 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002695 << handler.AccessKind << Field << !UnionField << UnionField;
2696 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002697 }
Richard Smithd62306a2011-11-10 06:34:14 +00002698 O = &O->getUnionValue();
2699 } else
2700 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002701
2702 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002703 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002704 if (WasConstQualified && !Field->isMutable())
2705 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002706
2707 if (ObjType.isVolatileQualified()) {
2708 if (Info.getLangOpts().CPlusPlus) {
2709 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002710 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002711 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002712 Info.Note(Field->getLocation(), diag::note_declared_at);
2713 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002714 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002715 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002716 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002717 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002718
2719 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002720 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002721 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002722 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2723 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2724 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002725
2726 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002727 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002728 if (WasConstQualified)
2729 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002730 }
2731 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002732}
2733
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002734namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002735struct ExtractSubobjectHandler {
2736 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002737 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002738
2739 static const AccessKinds AccessKind = AK_Read;
2740
2741 typedef bool result_type;
2742 bool failed() { return false; }
2743 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002744 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002745 return true;
2746 }
2747 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002748 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002749 return true;
2750 }
2751 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002752 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002753 return true;
2754 }
2755 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002756 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002757 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2758 return true;
2759 }
2760};
Richard Smith3229b742013-05-05 21:17:10 +00002761} // end anonymous namespace
2762
Richard Smith3da88fa2013-04-26 14:36:30 +00002763const AccessKinds ExtractSubobjectHandler::AccessKind;
2764
2765/// Extract the designated sub-object of an rvalue.
2766static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002767 const CompleteObject &Obj,
2768 const SubobjectDesignator &Sub,
2769 APValue &Result) {
2770 ExtractSubobjectHandler Handler = { Info, Result };
2771 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002772}
2773
Richard Smith3229b742013-05-05 21:17:10 +00002774namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002775struct ModifySubobjectHandler {
2776 EvalInfo &Info;
2777 APValue &NewVal;
2778 const Expr *E;
2779
2780 typedef bool result_type;
2781 static const AccessKinds AccessKind = AK_Assign;
2782
2783 bool checkConst(QualType QT) {
2784 // Assigning to a const object has undefined behavior.
2785 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002786 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002787 return false;
2788 }
2789 return true;
2790 }
2791
2792 bool failed() { return false; }
2793 bool found(APValue &Subobj, QualType SubobjType) {
2794 if (!checkConst(SubobjType))
2795 return false;
2796 // We've been given ownership of NewVal, so just swap it in.
2797 Subobj.swap(NewVal);
2798 return true;
2799 }
2800 bool found(APSInt &Value, QualType SubobjType) {
2801 if (!checkConst(SubobjType))
2802 return false;
2803 if (!NewVal.isInt()) {
2804 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002805 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002806 return false;
2807 }
2808 Value = NewVal.getInt();
2809 return true;
2810 }
2811 bool found(APFloat &Value, QualType SubobjType) {
2812 if (!checkConst(SubobjType))
2813 return false;
2814 Value = NewVal.getFloat();
2815 return true;
2816 }
2817 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2818 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2819 }
2820};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002821} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002822
Richard Smith3229b742013-05-05 21:17:10 +00002823const AccessKinds ModifySubobjectHandler::AccessKind;
2824
Richard Smith3da88fa2013-04-26 14:36:30 +00002825/// Update the designated sub-object of an rvalue to the given value.
2826static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002827 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002828 const SubobjectDesignator &Sub,
2829 APValue &NewVal) {
2830 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002831 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002832}
2833
Richard Smith84f6dcf2012-02-02 01:16:57 +00002834/// Find the position where two subobject designators diverge, or equivalently
2835/// the length of the common initial subsequence.
2836static unsigned FindDesignatorMismatch(QualType ObjType,
2837 const SubobjectDesignator &A,
2838 const SubobjectDesignator &B,
2839 bool &WasArrayIndex) {
2840 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2841 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002842 if (!ObjType.isNull() &&
2843 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002844 // Next subobject is an array element.
2845 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2846 WasArrayIndex = true;
2847 return I;
2848 }
Richard Smith66c96992012-02-18 22:04:06 +00002849 if (ObjType->isAnyComplexType())
2850 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2851 else
2852 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002853 } else {
2854 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2855 WasArrayIndex = false;
2856 return I;
2857 }
2858 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2859 // Next subobject is a field.
2860 ObjType = FD->getType();
2861 else
2862 // Next subobject is a base class.
2863 ObjType = QualType();
2864 }
2865 }
2866 WasArrayIndex = false;
2867 return I;
2868}
2869
2870/// Determine whether the given subobject designators refer to elements of the
2871/// same array object.
2872static bool AreElementsOfSameArray(QualType ObjType,
2873 const SubobjectDesignator &A,
2874 const SubobjectDesignator &B) {
2875 if (A.Entries.size() != B.Entries.size())
2876 return false;
2877
George Burgess IVa51c4072015-10-16 01:49:01 +00002878 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002879 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2880 // A is a subobject of the array element.
2881 return false;
2882
2883 // If A (and B) designates an array element, the last entry will be the array
2884 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2885 // of length 1' case, and the entire path must match.
2886 bool WasArrayIndex;
2887 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2888 return CommonLength >= A.Entries.size() - IsArray;
2889}
2890
Richard Smith3229b742013-05-05 21:17:10 +00002891/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002892static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2893 AccessKinds AK, const LValue &LVal,
2894 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002895 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002896 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002897 return CompleteObject();
2898 }
2899
Craig Topper36250ad2014-05-12 05:36:57 +00002900 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002901 if (LVal.CallIndex) {
2902 Frame = Info.getCallFrame(LVal.CallIndex);
2903 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002904 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002905 << AK << LVal.Base.is<const ValueDecl*>();
2906 NoteLValueLocation(Info, LVal.Base);
2907 return CompleteObject();
2908 }
Richard Smith3229b742013-05-05 21:17:10 +00002909 }
2910
2911 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2912 // is not a constant expression (even if the object is non-volatile). We also
2913 // apply this rule to C++98, in order to conform to the expected 'volatile'
2914 // semantics.
2915 if (LValType.isVolatileQualified()) {
2916 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002917 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002918 << AK << LValType;
2919 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002920 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002921 return CompleteObject();
2922 }
2923
2924 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002925 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002926 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002927
2928 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2929 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2930 // In C++11, constexpr, non-volatile variables initialized with constant
2931 // expressions are constant expressions too. Inside constexpr functions,
2932 // parameters are constant expressions even if they're non-const.
2933 // In C++1y, objects local to a constant expression (those with a Frame) are
2934 // both readable and writable inside constant expressions.
2935 // In C, such things can also be folded, although they are not ICEs.
2936 const VarDecl *VD = dyn_cast<VarDecl>(D);
2937 if (VD) {
2938 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2939 VD = VDef;
2940 }
2941 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002942 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002943 return CompleteObject();
2944 }
2945
2946 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002947 if (BaseType.isVolatileQualified()) {
2948 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002949 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002950 << AK << 1 << VD;
2951 Info.Note(VD->getLocation(), diag::note_declared_at);
2952 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002953 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002954 }
2955 return CompleteObject();
2956 }
2957
2958 // Unless we're looking at a local variable or argument in a constexpr call,
2959 // the variable we're reading must be const.
2960 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002961 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002962 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2963 // OK, we can read and modify an object if we're in the process of
2964 // evaluating its initializer, because its lifetime began in this
2965 // evaluation.
2966 } else if (AK != AK_Read) {
2967 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002968 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002969 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00002970 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002971 // OK, we can read this variable.
2972 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002973 // In OpenCL if a variable is in constant address space it is a const value.
2974 if (!(BaseType.isConstQualified() ||
2975 (Info.getLangOpts().OpenCL &&
2976 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002977 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002978 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002979 Info.Note(VD->getLocation(), diag::note_declared_at);
2980 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002981 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002982 }
2983 return CompleteObject();
2984 }
2985 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2986 // We support folding of const floating-point types, in order to make
2987 // static const data members of such types (supported as an extension)
2988 // more useful.
2989 if (Info.getLangOpts().CPlusPlus11) {
2990 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2991 Info.Note(VD->getLocation(), diag::note_declared_at);
2992 } else {
2993 Info.CCEDiag(E);
2994 }
George Burgess IVb5316982016-12-27 05:33:20 +00002995 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
2996 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
2997 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00002998 } else {
2999 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003000 if (Info.checkingPotentialConstantExpression() &&
3001 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3002 // The definition of this variable could be constexpr. We can't
3003 // access it right now, but may be able to in future.
3004 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003005 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003006 Info.Note(VD->getLocation(), diag::note_declared_at);
3007 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003008 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003009 }
3010 return CompleteObject();
3011 }
3012 }
3013
3014 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3015 return CompleteObject();
3016 } else {
3017 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3018
3019 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003020 if (const MaterializeTemporaryExpr *MTE =
3021 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3022 assert(MTE->getStorageDuration() == SD_Static &&
3023 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003024
Richard Smithe6c01442013-06-05 00:46:14 +00003025 // Per C++1y [expr.const]p2:
3026 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3027 // - a [...] glvalue of integral or enumeration type that refers to
3028 // a non-volatile const object [...]
3029 // [...]
3030 // - a [...] glvalue of literal type that refers to a non-volatile
3031 // object whose lifetime began within the evaluation of e.
3032 //
3033 // C++11 misses the 'began within the evaluation of e' check and
3034 // instead allows all temporaries, including things like:
3035 // int &&r = 1;
3036 // int x = ++r;
3037 // constexpr int k = r;
3038 // Therefore we use the C++1y rules in C++11 too.
3039 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3040 const ValueDecl *ED = MTE->getExtendingDecl();
3041 if (!(BaseType.isConstQualified() &&
3042 BaseType->isIntegralOrEnumerationType()) &&
3043 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003044 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003045 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3046 return CompleteObject();
3047 }
3048
3049 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3050 assert(BaseVal && "got reference to unevaluated temporary");
3051 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003052 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003053 return CompleteObject();
3054 }
3055 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003056 BaseVal = Frame->getTemporary(Base);
3057 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003058 }
Richard Smith3229b742013-05-05 21:17:10 +00003059
3060 // Volatile temporary objects cannot be accessed in constant expressions.
3061 if (BaseType.isVolatileQualified()) {
3062 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003063 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003064 << AK << 0;
3065 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3066 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003067 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003068 }
3069 return CompleteObject();
3070 }
3071 }
3072
Richard Smith7525ff62013-05-09 07:14:00 +00003073 // During the construction of an object, it is not yet 'const'.
3074 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3075 // and this doesn't do quite the right thing for const subobjects of the
3076 // object under construction.
3077 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3078 BaseType = Info.Ctx.getCanonicalType(BaseType);
3079 BaseType.removeLocalConst();
3080 }
3081
Richard Smith6d4c6582013-11-05 22:18:15 +00003082 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003083 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003084 //
3085 // FIXME: Not all local state is mutable. Allow local constant subobjects
3086 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003087 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3088 Info.EvalStatus.HasSideEffects) ||
3089 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003090 return CompleteObject();
3091
3092 return CompleteObject(BaseVal, BaseType);
3093}
3094
Richard Smith243ef902013-05-05 23:31:59 +00003095/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3096/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3097/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003098///
3099/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003100/// \param Conv - The expression for which we are performing the conversion.
3101/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003102/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3103/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003104/// \param LVal - The glvalue on which we are attempting to perform this action.
3105/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003106static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003107 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003108 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003109 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003110 return false;
3111
Richard Smith3229b742013-05-05 21:17:10 +00003112 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003113 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003114 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003115 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3116 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3117 // initializer until now for such expressions. Such an expression can't be
3118 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003119 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003120 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003121 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003122 }
Richard Smith3229b742013-05-05 21:17:10 +00003123 APValue Lit;
3124 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3125 return false;
3126 CompleteObject LitObj(&Lit, Base->getType());
3127 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003128 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003129 // We represent a string literal array as an lvalue pointing at the
3130 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003131 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003132 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3133 CompleteObject StrObj(&Str, Base->getType());
3134 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003135 }
Richard Smith11562c52011-10-28 17:51:58 +00003136 }
3137
Richard Smith3229b742013-05-05 21:17:10 +00003138 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3139 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003140}
3141
3142/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003143static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003144 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003145 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003146 return false;
3147
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003148 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003149 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003150 return false;
3151 }
3152
Richard Smith3229b742013-05-05 21:17:10 +00003153 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3154 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00003155}
3156
Richard Smith243ef902013-05-05 23:31:59 +00003157static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3158 return T->isSignedIntegerType() &&
3159 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3160}
3161
3162namespace {
Richard Smith43e77732013-05-07 04:50:00 +00003163struct CompoundAssignSubobjectHandler {
3164 EvalInfo &Info;
3165 const Expr *E;
3166 QualType PromotedLHSType;
3167 BinaryOperatorKind Opcode;
3168 const APValue &RHS;
3169
3170 static const AccessKinds AccessKind = AK_Assign;
3171
3172 typedef bool result_type;
3173
3174 bool checkConst(QualType QT) {
3175 // Assigning to a const object has undefined behavior.
3176 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003177 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003178 return false;
3179 }
3180 return true;
3181 }
3182
3183 bool failed() { return false; }
3184 bool found(APValue &Subobj, QualType SubobjType) {
3185 switch (Subobj.getKind()) {
3186 case APValue::Int:
3187 return found(Subobj.getInt(), SubobjType);
3188 case APValue::Float:
3189 return found(Subobj.getFloat(), SubobjType);
3190 case APValue::ComplexInt:
3191 case APValue::ComplexFloat:
3192 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003193 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003194 return false;
3195 case APValue::LValue:
3196 return foundPointer(Subobj, SubobjType);
3197 default:
3198 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003199 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003200 return false;
3201 }
3202 }
3203 bool found(APSInt &Value, QualType SubobjType) {
3204 if (!checkConst(SubobjType))
3205 return false;
3206
3207 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3208 // We don't support compound assignment on integer-cast-to-pointer
3209 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003210 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003211 return false;
3212 }
3213
3214 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3215 SubobjType, Value);
3216 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3217 return false;
3218 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3219 return true;
3220 }
3221 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003222 return checkConst(SubobjType) &&
3223 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3224 Value) &&
3225 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3226 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003227 }
3228 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3229 if (!checkConst(SubobjType))
3230 return false;
3231
3232 QualType PointeeType;
3233 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3234 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003235
3236 if (PointeeType.isNull() || !RHS.isInt() ||
3237 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003238 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003239 return false;
3240 }
3241
Richard Smithd6cc1982017-01-31 02:23:02 +00003242 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003243 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003244 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003245
3246 LValue LVal;
3247 LVal.setFrom(Info.Ctx, Subobj);
3248 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3249 return false;
3250 LVal.moveInto(Subobj);
3251 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003252 }
3253 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3254 llvm_unreachable("shouldn't encounter string elements here");
3255 }
3256};
3257} // end anonymous namespace
3258
3259const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3260
3261/// Perform a compound assignment of LVal <op>= RVal.
3262static bool handleCompoundAssignment(
3263 EvalInfo &Info, const Expr *E,
3264 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3265 BinaryOperatorKind Opcode, const APValue &RVal) {
3266 if (LVal.Designator.Invalid)
3267 return false;
3268
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003269 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003270 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003271 return false;
3272 }
3273
3274 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3275 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3276 RVal };
3277 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3278}
3279
3280namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003281struct IncDecSubobjectHandler {
3282 EvalInfo &Info;
3283 const Expr *E;
3284 AccessKinds AccessKind;
3285 APValue *Old;
3286
3287 typedef bool result_type;
3288
3289 bool checkConst(QualType QT) {
3290 // Assigning to a const object has undefined behavior.
3291 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003292 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003293 return false;
3294 }
3295 return true;
3296 }
3297
3298 bool failed() { return false; }
3299 bool found(APValue &Subobj, QualType SubobjType) {
3300 // Stash the old value. Also clear Old, so we don't clobber it later
3301 // if we're post-incrementing a complex.
3302 if (Old) {
3303 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003304 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003305 }
3306
3307 switch (Subobj.getKind()) {
3308 case APValue::Int:
3309 return found(Subobj.getInt(), SubobjType);
3310 case APValue::Float:
3311 return found(Subobj.getFloat(), SubobjType);
3312 case APValue::ComplexInt:
3313 return found(Subobj.getComplexIntReal(),
3314 SubobjType->castAs<ComplexType>()->getElementType()
3315 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3316 case APValue::ComplexFloat:
3317 return found(Subobj.getComplexFloatReal(),
3318 SubobjType->castAs<ComplexType>()->getElementType()
3319 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3320 case APValue::LValue:
3321 return foundPointer(Subobj, SubobjType);
3322 default:
3323 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003324 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003325 return false;
3326 }
3327 }
3328 bool found(APSInt &Value, QualType SubobjType) {
3329 if (!checkConst(SubobjType))
3330 return false;
3331
3332 if (!SubobjType->isIntegerType()) {
3333 // We don't support increment / decrement on integer-cast-to-pointer
3334 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003335 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003336 return false;
3337 }
3338
3339 if (Old) *Old = APValue(Value);
3340
3341 // bool arithmetic promotes to int, and the conversion back to bool
3342 // doesn't reduce mod 2^n, so special-case it.
3343 if (SubobjType->isBooleanType()) {
3344 if (AccessKind == AK_Increment)
3345 Value = 1;
3346 else
3347 Value = !Value;
3348 return true;
3349 }
3350
3351 bool WasNegative = Value.isNegative();
3352 if (AccessKind == AK_Increment) {
3353 ++Value;
3354
3355 if (!WasNegative && Value.isNegative() &&
3356 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3357 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003358 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003359 }
3360 } else {
3361 --Value;
3362
3363 if (WasNegative && !Value.isNegative() &&
3364 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3365 unsigned BitWidth = Value.getBitWidth();
3366 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3367 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003368 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003369 }
3370 }
3371 return true;
3372 }
3373 bool found(APFloat &Value, QualType SubobjType) {
3374 if (!checkConst(SubobjType))
3375 return false;
3376
3377 if (Old) *Old = APValue(Value);
3378
3379 APFloat One(Value.getSemantics(), 1);
3380 if (AccessKind == AK_Increment)
3381 Value.add(One, APFloat::rmNearestTiesToEven);
3382 else
3383 Value.subtract(One, APFloat::rmNearestTiesToEven);
3384 return true;
3385 }
3386 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3387 if (!checkConst(SubobjType))
3388 return false;
3389
3390 QualType PointeeType;
3391 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3392 PointeeType = PT->getPointeeType();
3393 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003394 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003395 return false;
3396 }
3397
3398 LValue LVal;
3399 LVal.setFrom(Info.Ctx, Subobj);
3400 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3401 AccessKind == AK_Increment ? 1 : -1))
3402 return false;
3403 LVal.moveInto(Subobj);
3404 return true;
3405 }
3406 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3407 llvm_unreachable("shouldn't encounter string elements here");
3408 }
3409};
3410} // end anonymous namespace
3411
3412/// Perform an increment or decrement on LVal.
3413static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3414 QualType LValType, bool IsIncrement, APValue *Old) {
3415 if (LVal.Designator.Invalid)
3416 return false;
3417
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003418 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003419 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003420 return false;
3421 }
3422
3423 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3424 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3425 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3426 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3427}
3428
Richard Smithe97cbd72011-11-11 04:05:33 +00003429/// Build an lvalue for the object argument of a member function call.
3430static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3431 LValue &This) {
3432 if (Object->getType()->isPointerType())
3433 return EvaluatePointer(Object, This, Info);
3434
3435 if (Object->isGLValue())
3436 return EvaluateLValue(Object, This, Info);
3437
Richard Smithd9f663b2013-04-22 15:31:51 +00003438 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003439 return EvaluateTemporary(Object, This, Info);
3440
Faisal Valie690b7a2016-07-02 22:34:24 +00003441 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003442 return false;
3443}
3444
3445/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3446/// lvalue referring to the result.
3447///
3448/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003449/// \param LV - An lvalue referring to the base of the member pointer.
3450/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003451/// \param IncludeMember - Specifies whether the member itself is included in
3452/// the resulting LValue subobject designator. This is not possible when
3453/// creating a bound member function.
3454/// \return The field or method declaration to which the member pointer refers,
3455/// or 0 if evaluation fails.
3456static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003457 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003458 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003459 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003460 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003461 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003462 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003463 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003464
3465 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3466 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003467 if (!MemPtr.getDecl()) {
3468 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003469 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003470 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003471 }
Richard Smith253c2a32012-01-27 01:14:48 +00003472
Richard Smith027bf112011-11-17 22:56:20 +00003473 if (MemPtr.isDerivedMember()) {
3474 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003475 // The end of the derived-to-base path for the base object must match the
3476 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003477 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003478 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003479 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003480 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003481 }
Richard Smith027bf112011-11-17 22:56:20 +00003482 unsigned PathLengthToMember =
3483 LV.Designator.Entries.size() - MemPtr.Path.size();
3484 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3485 const CXXRecordDecl *LVDecl = getAsBaseClass(
3486 LV.Designator.Entries[PathLengthToMember + I]);
3487 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003488 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003489 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003490 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003491 }
Richard Smith027bf112011-11-17 22:56:20 +00003492 }
3493
3494 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003495 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003496 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003497 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003498 } else if (!MemPtr.Path.empty()) {
3499 // Extend the LValue path with the member pointer's path.
3500 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3501 MemPtr.Path.size() + IncludeMember);
3502
3503 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003504 if (const PointerType *PT = LVType->getAs<PointerType>())
3505 LVType = PT->getPointeeType();
3506 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3507 assert(RD && "member pointer access on non-class-type expression");
3508 // The first class in the path is that of the lvalue.
3509 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3510 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003511 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003512 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003513 RD = Base;
3514 }
3515 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003516 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3517 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003518 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003519 }
3520
3521 // Add the member. Note that we cannot build bound member functions here.
3522 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003523 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003524 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003525 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003526 } else if (const IndirectFieldDecl *IFD =
3527 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003528 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003529 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003530 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003531 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003532 }
Richard Smith027bf112011-11-17 22:56:20 +00003533 }
3534
3535 return MemPtr.getDecl();
3536}
3537
Richard Smith84401042013-06-03 05:03:02 +00003538static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3539 const BinaryOperator *BO,
3540 LValue &LV,
3541 bool IncludeMember = true) {
3542 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3543
3544 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003545 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003546 MemberPtr MemPtr;
3547 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3548 }
Craig Topper36250ad2014-05-12 05:36:57 +00003549 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003550 }
3551
3552 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3553 BO->getRHS(), IncludeMember);
3554}
3555
Richard Smith027bf112011-11-17 22:56:20 +00003556/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3557/// the provided lvalue, which currently refers to the base object.
3558static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3559 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003560 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003561 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003562 return false;
3563
Richard Smitha8105bc2012-01-06 16:39:00 +00003564 QualType TargetQT = E->getType();
3565 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3566 TargetQT = PT->getPointeeType();
3567
3568 // Check this cast lands within the final derived-to-base subobject path.
3569 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003570 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003571 << D.MostDerivedType << TargetQT;
3572 return false;
3573 }
3574
Richard Smith027bf112011-11-17 22:56:20 +00003575 // Check the type of the final cast. We don't need to check the path,
3576 // since a cast can only be formed if the path is unique.
3577 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003578 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3579 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003580 if (NewEntriesSize == D.MostDerivedPathLength)
3581 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3582 else
Richard Smith027bf112011-11-17 22:56:20 +00003583 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003584 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003585 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003586 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003587 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003588 }
Richard Smith027bf112011-11-17 22:56:20 +00003589
3590 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003591 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003592}
3593
Mike Stump876387b2009-10-27 22:09:17 +00003594namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003595enum EvalStmtResult {
3596 /// Evaluation failed.
3597 ESR_Failed,
3598 /// Hit a 'return' statement.
3599 ESR_Returned,
3600 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003601 ESR_Succeeded,
3602 /// Hit a 'continue' statement.
3603 ESR_Continue,
3604 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003605 ESR_Break,
3606 /// Still scanning for 'case' or 'default' statement.
3607 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003608};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003609}
Richard Smith254a73d2011-10-28 22:34:42 +00003610
Richard Smith97fcf4b2016-08-14 23:15:52 +00003611static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3612 // We don't need to evaluate the initializer for a static local.
3613 if (!VD->hasLocalStorage())
3614 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003615
Richard Smith97fcf4b2016-08-14 23:15:52 +00003616 LValue Result;
3617 Result.set(VD, Info.CurrentCall->Index);
3618 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003619
Richard Smith97fcf4b2016-08-14 23:15:52 +00003620 const Expr *InitE = VD->getInit();
3621 if (!InitE) {
3622 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3623 << false << VD->getType();
3624 Val = APValue();
3625 return false;
3626 }
Richard Smith51f03172013-06-20 03:00:05 +00003627
Richard Smith97fcf4b2016-08-14 23:15:52 +00003628 if (InitE->isValueDependent())
3629 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003630
Richard Smith97fcf4b2016-08-14 23:15:52 +00003631 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3632 // Wipe out any partially-computed value, to allow tracking that this
3633 // evaluation failed.
3634 Val = APValue();
3635 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003636 }
3637
3638 return true;
3639}
3640
Richard Smith97fcf4b2016-08-14 23:15:52 +00003641static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3642 bool OK = true;
3643
3644 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3645 OK &= EvaluateVarDecl(Info, VD);
3646
3647 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3648 for (auto *BD : DD->bindings())
3649 if (auto *VD = BD->getHoldingVar())
3650 OK &= EvaluateDecl(Info, VD);
3651
3652 return OK;
3653}
3654
3655
Richard Smith4e18ca52013-05-06 05:56:11 +00003656/// Evaluate a condition (either a variable declaration or an expression).
3657static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3658 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003659 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003660 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3661 return false;
3662 return EvaluateAsBooleanCondition(Cond, Result, Info);
3663}
3664
Richard Smith89210072016-04-04 23:29:43 +00003665namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003666/// \brief A location where the result (returned value) of evaluating a
3667/// statement should be stored.
3668struct StmtResult {
3669 /// The APValue that should be filled in with the returned value.
3670 APValue &Value;
3671 /// The location containing the result, if any (used to support RVO).
3672 const LValue *Slot;
3673};
Richard Smith89210072016-04-04 23:29:43 +00003674}
Richard Smith52a980a2015-08-28 02:43:42 +00003675
3676static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003677 const Stmt *S,
3678 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003679
3680/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003681static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003682 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003683 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003684 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003685 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003686 case ESR_Break:
3687 return ESR_Succeeded;
3688 case ESR_Succeeded:
3689 case ESR_Continue:
3690 return ESR_Continue;
3691 case ESR_Failed:
3692 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003693 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003694 return ESR;
3695 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003696 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003697}
3698
Richard Smith496ddcf2013-05-12 17:32:42 +00003699/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003700static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003701 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003702 BlockScopeRAII Scope(Info);
3703
Richard Smith496ddcf2013-05-12 17:32:42 +00003704 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003705 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003706 {
3707 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003708 if (const Stmt *Init = SS->getInit()) {
3709 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3710 if (ESR != ESR_Succeeded)
3711 return ESR;
3712 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003713 if (SS->getConditionVariable() &&
3714 !EvaluateDecl(Info, SS->getConditionVariable()))
3715 return ESR_Failed;
3716 if (!EvaluateInteger(SS->getCond(), Value, Info))
3717 return ESR_Failed;
3718 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003719
3720 // Find the switch case corresponding to the value of the condition.
3721 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003722 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003723 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3724 SC = SC->getNextSwitchCase()) {
3725 if (isa<DefaultStmt>(SC)) {
3726 Found = SC;
3727 continue;
3728 }
3729
3730 const CaseStmt *CS = cast<CaseStmt>(SC);
3731 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3732 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3733 : LHS;
3734 if (LHS <= Value && Value <= RHS) {
3735 Found = SC;
3736 break;
3737 }
3738 }
3739
3740 if (!Found)
3741 return ESR_Succeeded;
3742
3743 // Search the switch body for the switch case and evaluate it from there.
3744 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3745 case ESR_Break:
3746 return ESR_Succeeded;
3747 case ESR_Succeeded:
3748 case ESR_Continue:
3749 case ESR_Failed:
3750 case ESR_Returned:
3751 return ESR;
3752 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003753 // This can only happen if the switch case is nested within a statement
3754 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003755 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003756 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003757 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003758 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003759}
3760
Richard Smith254a73d2011-10-28 22:34:42 +00003761// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003762static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003763 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003764 if (!Info.nextStep(S))
3765 return ESR_Failed;
3766
Richard Smith496ddcf2013-05-12 17:32:42 +00003767 // If we're hunting down a 'case' or 'default' label, recurse through
3768 // substatements until we hit the label.
3769 if (Case) {
3770 // FIXME: We don't start the lifetime of objects whose initialization we
3771 // jump over. However, such objects must be of class type with a trivial
3772 // default constructor that initialize all subobjects, so must be empty,
3773 // so this almost never matters.
3774 switch (S->getStmtClass()) {
3775 case Stmt::CompoundStmtClass:
3776 // FIXME: Precompute which substatement of a compound statement we
3777 // would jump to, and go straight there rather than performing a
3778 // linear scan each time.
3779 case Stmt::LabelStmtClass:
3780 case Stmt::AttributedStmtClass:
3781 case Stmt::DoStmtClass:
3782 break;
3783
3784 case Stmt::CaseStmtClass:
3785 case Stmt::DefaultStmtClass:
3786 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003787 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003788 break;
3789
3790 case Stmt::IfStmtClass: {
3791 // FIXME: Precompute which side of an 'if' we would jump to, and go
3792 // straight there rather than scanning both sides.
3793 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003794
3795 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3796 // preceded by our switch label.
3797 BlockScopeRAII Scope(Info);
3798
Richard Smith496ddcf2013-05-12 17:32:42 +00003799 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3800 if (ESR != ESR_CaseNotFound || !IS->getElse())
3801 return ESR;
3802 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3803 }
3804
3805 case Stmt::WhileStmtClass: {
3806 EvalStmtResult ESR =
3807 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3808 if (ESR != ESR_Continue)
3809 return ESR;
3810 break;
3811 }
3812
3813 case Stmt::ForStmtClass: {
3814 const ForStmt *FS = cast<ForStmt>(S);
3815 EvalStmtResult ESR =
3816 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3817 if (ESR != ESR_Continue)
3818 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003819 if (FS->getInc()) {
3820 FullExpressionRAII IncScope(Info);
3821 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3822 return ESR_Failed;
3823 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003824 break;
3825 }
3826
3827 case Stmt::DeclStmtClass:
3828 // FIXME: If the variable has initialization that can't be jumped over,
3829 // bail out of any immediately-surrounding compound-statement too.
3830 default:
3831 return ESR_CaseNotFound;
3832 }
3833 }
3834
Richard Smith254a73d2011-10-28 22:34:42 +00003835 switch (S->getStmtClass()) {
3836 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003837 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003838 // Don't bother evaluating beyond an expression-statement which couldn't
3839 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003840 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003841 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003842 return ESR_Failed;
3843 return ESR_Succeeded;
3844 }
3845
Faisal Valie690b7a2016-07-02 22:34:24 +00003846 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003847 return ESR_Failed;
3848
3849 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003850 return ESR_Succeeded;
3851
Richard Smithd9f663b2013-04-22 15:31:51 +00003852 case Stmt::DeclStmtClass: {
3853 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003854 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003855 // Each declaration initialization is its own full-expression.
3856 // FIXME: This isn't quite right; if we're performing aggregate
3857 // initialization, each braced subexpression is its own full-expression.
3858 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003859 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003860 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003861 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003862 return ESR_Succeeded;
3863 }
3864
Richard Smith357362d2011-12-13 06:39:58 +00003865 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003866 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003867 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003868 if (RetExpr &&
3869 !(Result.Slot
3870 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3871 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003872 return ESR_Failed;
3873 return ESR_Returned;
3874 }
Richard Smith254a73d2011-10-28 22:34:42 +00003875
3876 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003877 BlockScopeRAII Scope(Info);
3878
Richard Smith254a73d2011-10-28 22:34:42 +00003879 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003880 for (const auto *BI : CS->body()) {
3881 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003882 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003883 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003884 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003885 return ESR;
3886 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003887 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003888 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003889
3890 case Stmt::IfStmtClass: {
3891 const IfStmt *IS = cast<IfStmt>(S);
3892
3893 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003894 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003895 if (const Stmt *Init = IS->getInit()) {
3896 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3897 if (ESR != ESR_Succeeded)
3898 return ESR;
3899 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003900 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003901 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003902 return ESR_Failed;
3903
3904 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3905 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3906 if (ESR != ESR_Succeeded)
3907 return ESR;
3908 }
3909 return ESR_Succeeded;
3910 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003911
3912 case Stmt::WhileStmtClass: {
3913 const WhileStmt *WS = cast<WhileStmt>(S);
3914 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003915 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003916 bool Continue;
3917 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3918 Continue))
3919 return ESR_Failed;
3920 if (!Continue)
3921 break;
3922
3923 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3924 if (ESR != ESR_Continue)
3925 return ESR;
3926 }
3927 return ESR_Succeeded;
3928 }
3929
3930 case Stmt::DoStmtClass: {
3931 const DoStmt *DS = cast<DoStmt>(S);
3932 bool Continue;
3933 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003934 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003935 if (ESR != ESR_Continue)
3936 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003937 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003938
Richard Smith08d6a2c2013-07-24 07:11:57 +00003939 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003940 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3941 return ESR_Failed;
3942 } while (Continue);
3943 return ESR_Succeeded;
3944 }
3945
3946 case Stmt::ForStmtClass: {
3947 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003948 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003949 if (FS->getInit()) {
3950 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3951 if (ESR != ESR_Succeeded)
3952 return ESR;
3953 }
3954 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003955 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003956 bool Continue = true;
3957 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3958 FS->getCond(), Continue))
3959 return ESR_Failed;
3960 if (!Continue)
3961 break;
3962
3963 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3964 if (ESR != ESR_Continue)
3965 return ESR;
3966
Richard Smith08d6a2c2013-07-24 07:11:57 +00003967 if (FS->getInc()) {
3968 FullExpressionRAII IncScope(Info);
3969 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3970 return ESR_Failed;
3971 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003972 }
3973 return ESR_Succeeded;
3974 }
3975
Richard Smith896e0d72013-05-06 06:51:17 +00003976 case Stmt::CXXForRangeStmtClass: {
3977 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003978 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003979
3980 // Initialize the __range variable.
3981 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3982 if (ESR != ESR_Succeeded)
3983 return ESR;
3984
3985 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003986 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3987 if (ESR != ESR_Succeeded)
3988 return ESR;
3989 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003990 if (ESR != ESR_Succeeded)
3991 return ESR;
3992
3993 while (true) {
3994 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003995 {
3996 bool Continue = true;
3997 FullExpressionRAII CondExpr(Info);
3998 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3999 return ESR_Failed;
4000 if (!Continue)
4001 break;
4002 }
Richard Smith896e0d72013-05-06 06:51:17 +00004003
4004 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004005 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004006 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4007 if (ESR != ESR_Succeeded)
4008 return ESR;
4009
4010 // Loop body.
4011 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4012 if (ESR != ESR_Continue)
4013 return ESR;
4014
4015 // Increment: ++__begin
4016 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4017 return ESR_Failed;
4018 }
4019
4020 return ESR_Succeeded;
4021 }
4022
Richard Smith496ddcf2013-05-12 17:32:42 +00004023 case Stmt::SwitchStmtClass:
4024 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4025
Richard Smith4e18ca52013-05-06 05:56:11 +00004026 case Stmt::ContinueStmtClass:
4027 return ESR_Continue;
4028
4029 case Stmt::BreakStmtClass:
4030 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004031
4032 case Stmt::LabelStmtClass:
4033 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4034
4035 case Stmt::AttributedStmtClass:
4036 // As a general principle, C++11 attributes can be ignored without
4037 // any semantic impact.
4038 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4039 Case);
4040
4041 case Stmt::CaseStmtClass:
4042 case Stmt::DefaultStmtClass:
4043 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004044 }
4045}
4046
Richard Smithcc36f692011-12-22 02:22:31 +00004047/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4048/// default constructor. If so, we'll fold it whether or not it's marked as
4049/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4050/// so we need special handling.
4051static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004052 const CXXConstructorDecl *CD,
4053 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004054 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4055 return false;
4056
Richard Smith66e05fe2012-01-18 05:21:49 +00004057 // Value-initialization does not call a trivial default constructor, so such a
4058 // call is a core constant expression whether or not the constructor is
4059 // constexpr.
4060 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004061 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004062 // FIXME: If DiagDecl is an implicitly-declared special member function,
4063 // we should be much more explicit about why it's not constexpr.
4064 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4065 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4066 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004067 } else {
4068 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4069 }
4070 }
4071 return true;
4072}
4073
Richard Smith357362d2011-12-13 06:39:58 +00004074/// CheckConstexprFunction - Check that a function can be called in a constant
4075/// expression.
4076static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4077 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004078 const FunctionDecl *Definition,
4079 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004080 // Potential constant expressions can contain calls to declared, but not yet
4081 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004082 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004083 Declaration->isConstexpr())
4084 return false;
4085
Richard Smith0838f3a2013-05-14 05:18:44 +00004086 // Bail out with no diagnostic if the function declaration itself is invalid.
4087 // We will have produced a relevant diagnostic while parsing it.
4088 if (Declaration->isInvalidDecl())
4089 return false;
4090
Richard Smith357362d2011-12-13 06:39:58 +00004091 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004092 if (Definition && Definition->isConstexpr() &&
4093 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004094 return true;
4095
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004096 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004097 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Faisal Valie690b7a2016-07-02 22:34:24 +00004098
Richard Smith5179eb72016-06-28 19:03:57 +00004099 // If this function is not constexpr because it is an inherited
4100 // non-constexpr constructor, diagnose that directly.
4101 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4102 if (CD && CD->isInheritingConstructor()) {
4103 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4104 if (!Inherited->isConstexpr())
4105 DiagDecl = CD = Inherited;
4106 }
4107
4108 // FIXME: If DiagDecl is an implicitly-declared special member function
4109 // or an inheriting constructor, we should be much more explicit about why
4110 // it's not constexpr.
4111 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004112 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004113 << CD->getInheritedConstructor().getConstructor()->getParent();
4114 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004115 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004116 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004117 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4118 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004119 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004120 }
4121 return false;
4122}
4123
Richard Smithbe6dd812014-11-19 21:27:17 +00004124/// Determine if a class has any fields that might need to be copied by a
4125/// trivial copy or move operation.
4126static bool hasFields(const CXXRecordDecl *RD) {
4127 if (!RD || RD->isEmpty())
4128 return false;
4129 for (auto *FD : RD->fields()) {
4130 if (FD->isUnnamedBitfield())
4131 continue;
4132 return true;
4133 }
4134 for (auto &Base : RD->bases())
4135 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4136 return true;
4137 return false;
4138}
4139
Richard Smithd62306a2011-11-10 06:34:14 +00004140namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004141typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004142}
4143
4144/// EvaluateArgs - Evaluate the arguments to a function call.
4145static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4146 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004147 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004148 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004149 I != E; ++I) {
4150 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4151 // If we're checking for a potential constant expression, evaluate all
4152 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004153 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004154 return false;
4155 Success = false;
4156 }
4157 }
4158 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004159}
4160
Richard Smith254a73d2011-10-28 22:34:42 +00004161/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004162static bool HandleFunctionCall(SourceLocation CallLoc,
4163 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004164 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004165 EvalInfo &Info, APValue &Result,
4166 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004167 ArgVector ArgValues(Args.size());
4168 if (!EvaluateArgs(Args, ArgValues, Info))
4169 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004170
Richard Smith253c2a32012-01-27 01:14:48 +00004171 if (!Info.CheckCallLimit(CallLoc))
4172 return false;
4173
4174 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004175
4176 // For a trivial copy or move assignment, perform an APValue copy. This is
4177 // essential for unions, where the operations performed by the assignment
4178 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004179 //
4180 // Skip this for non-union classes with no fields; in that case, the defaulted
4181 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004182 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004183 if (MD && MD->isDefaulted() &&
4184 (MD->getParent()->isUnion() ||
4185 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004186 assert(This &&
4187 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4188 LValue RHS;
4189 RHS.setFrom(Info.Ctx, ArgValues[0]);
4190 APValue RHSValue;
4191 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4192 RHS, RHSValue))
4193 return false;
4194 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4195 RHSValue))
4196 return false;
4197 This->moveInto(Result);
4198 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004199 } else if (MD && isLambdaCallOperator(MD)) {
4200 // We're in a lambda; determine the lambda capture field maps.
4201 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4202 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004203 }
4204
Richard Smith52a980a2015-08-28 02:43:42 +00004205 StmtResult Ret = {Result, ResultSlot};
4206 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004207 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004208 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004209 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004210 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004211 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004212 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004213}
4214
Richard Smithd62306a2011-11-10 06:34:14 +00004215/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004216static bool HandleConstructorCall(const Expr *E, const LValue &This,
4217 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004218 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004219 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004220 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004221 if (!Info.CheckCallLimit(CallLoc))
4222 return false;
4223
Richard Smith3607ffe2012-02-13 03:54:03 +00004224 const CXXRecordDecl *RD = Definition->getParent();
4225 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004226 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004227 return false;
4228 }
4229
Richard Smith5179eb72016-06-28 19:03:57 +00004230 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004231
Richard Smith52a980a2015-08-28 02:43:42 +00004232 // FIXME: Creating an APValue just to hold a nonexistent return value is
4233 // wasteful.
4234 APValue RetVal;
4235 StmtResult Ret = {RetVal, nullptr};
4236
Richard Smith5179eb72016-06-28 19:03:57 +00004237 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004238 if (Definition->isDelegatingConstructor()) {
4239 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004240 {
4241 FullExpressionRAII InitScope(Info);
4242 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4243 return false;
4244 }
Richard Smith52a980a2015-08-28 02:43:42 +00004245 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004246 }
4247
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004248 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004249 // essential for unions (or classes with anonymous union members), where the
4250 // operations performed by the constructor cannot be represented by
4251 // ctor-initializers.
4252 //
4253 // Skip this for empty non-union classes; we should not perform an
4254 // lvalue-to-rvalue conversion on them because their copy constructor does not
4255 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004256 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004257 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004258 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004259 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004260 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004261 return handleLValueToRValueConversion(
4262 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4263 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004264 }
4265
4266 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004267 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004268 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004269 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004270
John McCalld7bca762012-05-01 00:38:49 +00004271 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004272 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4273
Richard Smith08d6a2c2013-07-24 07:11:57 +00004274 // A scope for temporaries lifetime-extended by reference members.
4275 BlockScopeRAII LifetimeExtendedScope(Info);
4276
Richard Smith253c2a32012-01-27 01:14:48 +00004277 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004278 unsigned BasesSeen = 0;
4279#ifndef NDEBUG
4280 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4281#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004282 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004283 LValue Subobject = This;
4284 APValue *Value = &Result;
4285
4286 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004287 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004288 if (I->isBaseInitializer()) {
4289 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004290#ifndef NDEBUG
4291 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004292 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004293 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4294 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4295 "base class initializers not in expected order");
4296 ++BaseIt;
4297#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004298 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004299 BaseType->getAsCXXRecordDecl(), &Layout))
4300 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004301 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004302 } else if ((FD = I->getMember())) {
4303 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004304 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004305 if (RD->isUnion()) {
4306 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004307 Value = &Result.getUnionValue();
4308 } else {
4309 Value = &Result.getStructField(FD->getFieldIndex());
4310 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004311 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004312 // Walk the indirect field decl's chain to find the object to initialize,
4313 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004314 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004315 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004316 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4317 // Switch the union field if it differs. This happens if we had
4318 // preceding zero-initialization, and we're now initializing a union
4319 // subobject other than the first.
4320 // FIXME: In this case, the values of the other subobjects are
4321 // specified, since zero-initialization sets all padding bits to zero.
4322 if (Value->isUninit() ||
4323 (Value->isUnion() && Value->getUnionField() != FD)) {
4324 if (CD->isUnion())
4325 *Value = APValue(FD);
4326 else
4327 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004328 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004329 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004330 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004331 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004332 if (CD->isUnion())
4333 Value = &Value->getUnionValue();
4334 else
4335 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004336 }
Richard Smithd62306a2011-11-10 06:34:14 +00004337 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004338 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004339 }
Richard Smith253c2a32012-01-27 01:14:48 +00004340
Richard Smith08d6a2c2013-07-24 07:11:57 +00004341 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004342 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4343 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004344 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004345 // If we're checking for a potential constant expression, evaluate all
4346 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004347 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004348 return false;
4349 Success = false;
4350 }
Richard Smithd62306a2011-11-10 06:34:14 +00004351 }
4352
Richard Smithd9f663b2013-04-22 15:31:51 +00004353 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004354 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004355}
4356
Richard Smith5179eb72016-06-28 19:03:57 +00004357static bool HandleConstructorCall(const Expr *E, const LValue &This,
4358 ArrayRef<const Expr*> Args,
4359 const CXXConstructorDecl *Definition,
4360 EvalInfo &Info, APValue &Result) {
4361 ArgVector ArgValues(Args.size());
4362 if (!EvaluateArgs(Args, ArgValues, Info))
4363 return false;
4364
4365 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4366 Info, Result);
4367}
4368
Eli Friedman9a156e52008-11-12 09:44:48 +00004369//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004370// Generic Evaluation
4371//===----------------------------------------------------------------------===//
4372namespace {
4373
Aaron Ballman68af21c2014-01-03 19:26:43 +00004374template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004375class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004376 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004377private:
Richard Smith52a980a2015-08-28 02:43:42 +00004378 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004379 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004380 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004381 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004382 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004383 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004384 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004385
Richard Smith17100ba2012-02-16 02:46:34 +00004386 // Check whether a conditional operator with a non-constant condition is a
4387 // potential constant expression. If neither arm is a potential constant
4388 // expression, then the conditional operator is not either.
4389 template<typename ConditionalOperator>
4390 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004391 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004392
4393 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004394 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004395 {
Richard Smith17100ba2012-02-16 02:46:34 +00004396 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004397 StmtVisitorTy::Visit(E->getFalseExpr());
4398 if (Diag.empty())
4399 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004400 }
Richard Smith17100ba2012-02-16 02:46:34 +00004401
George Burgess IV8c892b52016-05-25 22:31:54 +00004402 {
4403 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004404 Diag.clear();
4405 StmtVisitorTy::Visit(E->getTrueExpr());
4406 if (Diag.empty())
4407 return;
4408 }
4409
4410 Error(E, diag::note_constexpr_conditional_never_const);
4411 }
4412
4413
4414 template<typename ConditionalOperator>
4415 bool HandleConditionalOperator(const ConditionalOperator *E) {
4416 bool BoolResult;
4417 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004418 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004419 CheckPotentialConstantConditional(E);
4420 return false;
4421 }
4422
4423 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4424 return StmtVisitorTy::Visit(EvalExpr);
4425 }
4426
Peter Collingbournee9200682011-05-13 03:29:01 +00004427protected:
4428 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004429 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004430 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4431
Richard Smith92b1ce02011-12-12 09:28:41 +00004432 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004433 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004434 }
4435
Aaron Ballman68af21c2014-01-03 19:26:43 +00004436 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004437
4438public:
4439 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4440
4441 EvalInfo &getEvalInfo() { return Info; }
4442
Richard Smithf57d8cb2011-12-09 22:58:01 +00004443 /// Report an evaluation error. This should only be called when an error is
4444 /// first discovered. When propagating an error, just return false.
4445 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004446 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004447 return false;
4448 }
4449 bool Error(const Expr *E) {
4450 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4451 }
4452
Aaron Ballman68af21c2014-01-03 19:26:43 +00004453 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004454 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004455 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004456 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004457 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004458 }
4459
Aaron Ballman68af21c2014-01-03 19:26:43 +00004460 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004461 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004462 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004463 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004464 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004465 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004466 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004467 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004468 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004469 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004470 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004471 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004472 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004473 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004474 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004475 // The initializer may not have been parsed yet, or might be erroneous.
4476 if (!E->getExpr())
4477 return Error(E);
4478 return StmtVisitorTy::Visit(E->getExpr());
4479 }
Richard Smith5894a912011-12-19 22:12:41 +00004480 // We cannot create any objects for which cleanups are required, so there is
4481 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004482 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004483 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004484
Aaron Ballman68af21c2014-01-03 19:26:43 +00004485 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004486 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4487 return static_cast<Derived*>(this)->VisitCastExpr(E);
4488 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004489 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004490 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4491 return static_cast<Derived*>(this)->VisitCastExpr(E);
4492 }
4493
Aaron Ballman68af21c2014-01-03 19:26:43 +00004494 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004495 switch (E->getOpcode()) {
4496 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004497 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004498
4499 case BO_Comma:
4500 VisitIgnoredValue(E->getLHS());
4501 return StmtVisitorTy::Visit(E->getRHS());
4502
4503 case BO_PtrMemD:
4504 case BO_PtrMemI: {
4505 LValue Obj;
4506 if (!HandleMemberPointerAccess(Info, E, Obj))
4507 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004508 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004509 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004510 return false;
4511 return DerivedSuccess(Result, E);
4512 }
4513 }
4514 }
4515
Aaron Ballman68af21c2014-01-03 19:26:43 +00004516 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004517 // Evaluate and cache the common expression. We treat it as a temporary,
4518 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004519 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004520 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004521 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004522
Richard Smith17100ba2012-02-16 02:46:34 +00004523 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004524 }
4525
Aaron Ballman68af21c2014-01-03 19:26:43 +00004526 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004527 bool IsBcpCall = false;
4528 // If the condition (ignoring parens) is a __builtin_constant_p call,
4529 // the result is a constant expression if it can be folded without
4530 // side-effects. This is an important GNU extension. See GCC PR38377
4531 // for discussion.
4532 if (const CallExpr *CallCE =
4533 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004534 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004535 IsBcpCall = true;
4536
4537 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4538 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004539 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004540 return false;
4541
Richard Smith6d4c6582013-11-05 22:18:15 +00004542 FoldConstant Fold(Info, IsBcpCall);
4543 if (!HandleConditionalOperator(E)) {
4544 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004545 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004546 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004547
4548 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004549 }
4550
Aaron Ballman68af21c2014-01-03 19:26:43 +00004551 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004552 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4553 return DerivedSuccess(*Value, E);
4554
4555 const Expr *Source = E->getSourceExpr();
4556 if (!Source)
4557 return Error(E);
4558 if (Source == E) { // sanity checking.
4559 assert(0 && "OpaqueValueExpr recursively refers to itself");
4560 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004561 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004562 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004563 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004564
Aaron Ballman68af21c2014-01-03 19:26:43 +00004565 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004566 APValue Result;
4567 if (!handleCallExpr(E, Result, nullptr))
4568 return false;
4569 return DerivedSuccess(Result, E);
4570 }
4571
4572 bool handleCallExpr(const CallExpr *E, APValue &Result,
4573 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004574 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004575 QualType CalleeType = Callee->getType();
4576
Craig Topper36250ad2014-05-12 05:36:57 +00004577 const FunctionDecl *FD = nullptr;
4578 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004579 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004580 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004581
Richard Smithe97cbd72011-11-11 04:05:33 +00004582 // Extract function decl and 'this' pointer from the callee.
4583 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004584 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004585 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4586 // Explicit bound member calls, such as x.f() or p->g();
4587 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004588 return false;
4589 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004590 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004591 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004592 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4593 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004594 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4595 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004596 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004597 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004598 return Error(Callee);
4599
4600 FD = dyn_cast<FunctionDecl>(Member);
4601 if (!FD)
4602 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004603 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004604 LValue Call;
4605 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004606 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004607
Richard Smitha8105bc2012-01-06 16:39:00 +00004608 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004609 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004610 FD = dyn_cast_or_null<FunctionDecl>(
4611 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004612 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004613 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004614 // Don't call function pointers which have been cast to some other type.
4615 // Per DR (no number yet), the caller and callee can differ in noexcept.
4616 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4617 CalleeType->getPointeeType(), FD->getType())) {
4618 return Error(E);
4619 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004620
4621 // Overloaded operator calls to member functions are represented as normal
4622 // calls with '*this' as the first argument.
4623 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4624 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004625 // FIXME: When selecting an implicit conversion for an overloaded
4626 // operator delete, we sometimes try to evaluate calls to conversion
4627 // operators without a 'this' parameter!
4628 if (Args.empty())
4629 return Error(E);
4630
Richard Smithe97cbd72011-11-11 04:05:33 +00004631 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4632 return false;
4633 This = &ThisVal;
4634 Args = Args.slice(1);
Faisal Valid92e7492017-01-08 18:56:11 +00004635 } else if (MD && MD->isLambdaStaticInvoker()) {
4636 // Map the static invoker for the lambda back to the call operator.
4637 // Conveniently, we don't have to slice out the 'this' argument (as is
4638 // being done for the non-static case), since a static member function
4639 // doesn't have an implicit argument passed in.
4640 const CXXRecordDecl *ClosureClass = MD->getParent();
4641 assert(
4642 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4643 "Number of captures must be zero for conversion to function-ptr");
4644
4645 const CXXMethodDecl *LambdaCallOp =
4646 ClosureClass->getLambdaCallOperator();
4647
4648 // Set 'FD', the function that will be called below, to the call
4649 // operator. If the closure object represents a generic lambda, find
4650 // the corresponding specialization of the call operator.
4651
4652 if (ClosureClass->isGenericLambda()) {
4653 assert(MD->isFunctionTemplateSpecialization() &&
4654 "A generic lambda's static-invoker function must be a "
4655 "template specialization");
4656 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4657 FunctionTemplateDecl *CallOpTemplate =
4658 LambdaCallOp->getDescribedFunctionTemplate();
4659 void *InsertPos = nullptr;
4660 FunctionDecl *CorrespondingCallOpSpecialization =
4661 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4662 assert(CorrespondingCallOpSpecialization &&
4663 "We must always have a function call operator specialization "
4664 "that corresponds to our static invoker specialization");
4665 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4666 } else
4667 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004668 }
4669
Faisal Valid92e7492017-01-08 18:56:11 +00004670
Richard Smithe97cbd72011-11-11 04:05:33 +00004671 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004672 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004673
Richard Smith47b34932012-02-01 02:39:43 +00004674 if (This && !This->checkSubobject(Info, E, CSK_This))
4675 return false;
4676
Richard Smith3607ffe2012-02-13 03:54:03 +00004677 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4678 // calls to such functions in constant expressions.
4679 if (This && !HasQualifier &&
4680 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4681 return Error(E, diag::note_constexpr_virtual_call);
4682
Craig Topper36250ad2014-05-12 05:36:57 +00004683 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004684 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004685
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004686 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004687 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4688 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004689 return false;
4690
Richard Smith52a980a2015-08-28 02:43:42 +00004691 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004692 }
4693
Aaron Ballman68af21c2014-01-03 19:26:43 +00004694 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004695 return StmtVisitorTy::Visit(E->getInitializer());
4696 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004697 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004698 if (E->getNumInits() == 0)
4699 return DerivedZeroInitialization(E);
4700 if (E->getNumInits() == 1)
4701 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004702 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004703 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004704 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004705 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004706 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004707 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004708 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004709 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004710 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004711 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004712 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004713
Richard Smithd62306a2011-11-10 06:34:14 +00004714 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004715 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004716 assert(!E->isArrow() && "missing call to bound member function?");
4717
Richard Smith2e312c82012-03-03 22:46:17 +00004718 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004719 if (!Evaluate(Val, Info, E->getBase()))
4720 return false;
4721
4722 QualType BaseTy = E->getBase()->getType();
4723
4724 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004725 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004726 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004727 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004728 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4729
Richard Smith3229b742013-05-05 21:17:10 +00004730 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004731 SubobjectDesignator Designator(BaseTy);
4732 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004733
Richard Smith3229b742013-05-05 21:17:10 +00004734 APValue Result;
4735 return extractSubobject(Info, E, Obj, Designator, Result) &&
4736 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004737 }
4738
Aaron Ballman68af21c2014-01-03 19:26:43 +00004739 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004740 switch (E->getCastKind()) {
4741 default:
4742 break;
4743
Richard Smitha23ab512013-05-23 00:30:41 +00004744 case CK_AtomicToNonAtomic: {
4745 APValue AtomicVal;
4746 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4747 return false;
4748 return DerivedSuccess(AtomicVal, E);
4749 }
4750
Richard Smith11562c52011-10-28 17:51:58 +00004751 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004752 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004753 return StmtVisitorTy::Visit(E->getSubExpr());
4754
4755 case CK_LValueToRValue: {
4756 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004757 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4758 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004759 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004760 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004761 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004762 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004763 return false;
4764 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004765 }
4766 }
4767
Richard Smithf57d8cb2011-12-09 22:58:01 +00004768 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004769 }
4770
Aaron Ballman68af21c2014-01-03 19:26:43 +00004771 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004772 return VisitUnaryPostIncDec(UO);
4773 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004774 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004775 return VisitUnaryPostIncDec(UO);
4776 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004777 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004778 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004779 return Error(UO);
4780
4781 LValue LVal;
4782 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4783 return false;
4784 APValue RVal;
4785 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4786 UO->isIncrementOp(), &RVal))
4787 return false;
4788 return DerivedSuccess(RVal, UO);
4789 }
4790
Aaron Ballman68af21c2014-01-03 19:26:43 +00004791 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004792 // We will have checked the full-expressions inside the statement expression
4793 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004794 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004795 return Error(E);
4796
Richard Smith08d6a2c2013-07-24 07:11:57 +00004797 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004798 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004799 if (CS->body_empty())
4800 return true;
4801
Richard Smith51f03172013-06-20 03:00:05 +00004802 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4803 BE = CS->body_end();
4804 /**/; ++BI) {
4805 if (BI + 1 == BE) {
4806 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4807 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004808 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004809 diag::note_constexpr_stmt_expr_unsupported);
4810 return false;
4811 }
4812 return this->Visit(FinalExpr);
4813 }
4814
4815 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004816 StmtResult Result = { ReturnValue, nullptr };
4817 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004818 if (ESR != ESR_Succeeded) {
4819 // FIXME: If the statement-expression terminated due to 'return',
4820 // 'break', or 'continue', it would be nice to propagate that to
4821 // the outer statement evaluation rather than bailing out.
4822 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004823 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004824 diag::note_constexpr_stmt_expr_unsupported);
4825 return false;
4826 }
4827 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004828
4829 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004830 }
4831
Richard Smith4a678122011-10-24 18:44:57 +00004832 /// Visit a value which is evaluated, but whose value is ignored.
4833 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004834 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004835 }
David Majnemere9807b22016-02-26 04:23:19 +00004836
4837 /// Potentially visit a MemberExpr's base expression.
4838 void VisitIgnoredBaseExpression(const Expr *E) {
4839 // While MSVC doesn't evaluate the base expression, it does diagnose the
4840 // presence of side-effecting behavior.
4841 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4842 return;
4843 VisitIgnoredValue(E);
4844 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004845};
4846
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004847}
Peter Collingbournee9200682011-05-13 03:29:01 +00004848
4849//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004850// Common base class for lvalue and temporary evaluation.
4851//===----------------------------------------------------------------------===//
4852namespace {
4853template<class Derived>
4854class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004855 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004856protected:
4857 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00004858 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00004859 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004860 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004861
4862 bool Success(APValue::LValueBase B) {
4863 Result.set(B);
4864 return true;
4865 }
4866
George Burgess IVf9013bf2017-02-10 22:52:29 +00004867 bool evaluatePointer(const Expr *E, LValue &Result) {
4868 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4869 }
4870
Richard Smith027bf112011-11-17 22:56:20 +00004871public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004872 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4873 : ExprEvaluatorBaseTy(Info), Result(Result),
4874 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00004875
Richard Smith2e312c82012-03-03 22:46:17 +00004876 bool Success(const APValue &V, const Expr *E) {
4877 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004878 return true;
4879 }
Richard Smith027bf112011-11-17 22:56:20 +00004880
Richard Smith027bf112011-11-17 22:56:20 +00004881 bool VisitMemberExpr(const MemberExpr *E) {
4882 // Handle non-static data members.
4883 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004884 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004885 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004886 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00004887 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004888 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004889 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004890 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004891 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004892 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004893 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004894 BaseTy = E->getBase()->getType();
4895 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004896 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004897 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004898 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004899 Result.setInvalid(E);
4900 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004901 }
Richard Smith027bf112011-11-17 22:56:20 +00004902
Richard Smith1b78b3d2012-01-25 22:15:11 +00004903 const ValueDecl *MD = E->getMemberDecl();
4904 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4905 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4906 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4907 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004908 if (!HandleLValueMember(this->Info, E, Result, FD))
4909 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004910 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004911 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4912 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004913 } else
4914 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004915
Richard Smith1b78b3d2012-01-25 22:15:11 +00004916 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004917 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004918 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004919 RefValue))
4920 return false;
4921 return Success(RefValue, E);
4922 }
4923 return true;
4924 }
4925
4926 bool VisitBinaryOperator(const BinaryOperator *E) {
4927 switch (E->getOpcode()) {
4928 default:
4929 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4930
4931 case BO_PtrMemD:
4932 case BO_PtrMemI:
4933 return HandleMemberPointerAccess(this->Info, E, Result);
4934 }
4935 }
4936
4937 bool VisitCastExpr(const CastExpr *E) {
4938 switch (E->getCastKind()) {
4939 default:
4940 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4941
4942 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004943 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004944 if (!this->Visit(E->getSubExpr()))
4945 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004946
4947 // Now figure out the necessary offset to add to the base LV to get from
4948 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004949 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4950 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004951 }
4952 }
4953};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004954}
Richard Smith027bf112011-11-17 22:56:20 +00004955
4956//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004957// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004958//
4959// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4960// function designators (in C), decl references to void objects (in C), and
4961// temporaries (if building with -Wno-address-of-temporary).
4962//
4963// LValue evaluation produces values comprising a base expression of one of the
4964// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004965// - Declarations
4966// * VarDecl
4967// * FunctionDecl
4968// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00004969// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00004970// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004971// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004972// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004973// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004974// * ObjCEncodeExpr
4975// * AddrLabelExpr
4976// * BlockExpr
4977// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004978// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004979// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004980// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004981// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4982// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004983// * A MaterializeTemporaryExpr that has static storage duration, with no
4984// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004985// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004986//===----------------------------------------------------------------------===//
4987namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004988class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004989 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004990public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004991 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
4992 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00004993
Richard Smith11562c52011-10-28 17:51:58 +00004994 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004995 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004996
Peter Collingbournee9200682011-05-13 03:29:01 +00004997 bool VisitDeclRefExpr(const DeclRefExpr *E);
4998 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004999 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005000 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5001 bool VisitMemberExpr(const MemberExpr *E);
5002 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5003 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005004 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005005 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005006 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5007 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005008 bool VisitUnaryReal(const UnaryOperator *E);
5009 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005010 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5011 return VisitUnaryPreIncDec(UO);
5012 }
5013 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5014 return VisitUnaryPreIncDec(UO);
5015 }
Richard Smith3229b742013-05-05 21:17:10 +00005016 bool VisitBinAssign(const BinaryOperator *BO);
5017 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005018
Peter Collingbournee9200682011-05-13 03:29:01 +00005019 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005020 switch (E->getCastKind()) {
5021 default:
Richard Smith027bf112011-11-17 22:56:20 +00005022 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005023
Eli Friedmance3e02a2011-10-11 00:13:24 +00005024 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005025 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005026 if (!Visit(E->getSubExpr()))
5027 return false;
5028 Result.Designator.setInvalid();
5029 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005030
Richard Smith027bf112011-11-17 22:56:20 +00005031 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005032 if (!Visit(E->getSubExpr()))
5033 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005034 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005035 }
5036 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005037};
5038} // end anonymous namespace
5039
Richard Smith11562c52011-10-28 17:51:58 +00005040/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005041/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005042/// * function designators in C, and
5043/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005044/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005045static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5046 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005047 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005048 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005049 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005050}
5051
Peter Collingbournee9200682011-05-13 03:29:01 +00005052bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005053 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005054 return Success(FD);
5055 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005056 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005057 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005058 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005059 return Error(E);
5060}
Richard Smith733237d2011-10-24 23:14:33 +00005061
Faisal Vali0528a312016-11-13 06:09:16 +00005062
Richard Smith11562c52011-10-28 17:51:58 +00005063bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005064
5065 // If we are within a lambda's call operator, check whether the 'VD' referred
5066 // to within 'E' actually represents a lambda-capture that maps to a
5067 // data-member/field within the closure object, and if so, evaluate to the
5068 // field or what the field refers to.
5069 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5070 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5071 if (Info.checkingPotentialConstantExpression())
5072 return false;
5073 // Start with 'Result' referring to the complete closure object...
5074 Result = *Info.CurrentCall->This;
5075 // ... then update it to refer to the field of the closure object
5076 // that represents the capture.
5077 if (!HandleLValueMember(Info, E, Result, FD))
5078 return false;
5079 // And if the field is of reference type, update 'Result' to refer to what
5080 // the field refers to.
5081 if (FD->getType()->isReferenceType()) {
5082 APValue RVal;
5083 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5084 RVal))
5085 return false;
5086 Result.setFrom(Info.Ctx, RVal);
5087 }
5088 return true;
5089 }
5090 }
Craig Topper36250ad2014-05-12 05:36:57 +00005091 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005092 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5093 // Only if a local variable was declared in the function currently being
5094 // evaluated, do we expect to be able to find its value in the current
5095 // frame. (Otherwise it was likely declared in an enclosing context and
5096 // could either have a valid evaluatable value (for e.g. a constexpr
5097 // variable) or be ill-formed (and trigger an appropriate evaluation
5098 // diagnostic)).
5099 if (Info.CurrentCall->Callee &&
5100 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5101 Frame = Info.CurrentCall;
5102 }
5103 }
Richard Smith3229b742013-05-05 21:17:10 +00005104
Richard Smithfec09922011-11-01 16:57:24 +00005105 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005106 if (Frame) {
5107 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005108 return true;
5109 }
Richard Smithce40ad62011-11-12 22:28:03 +00005110 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005111 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005112
Richard Smith3229b742013-05-05 21:17:10 +00005113 APValue *V;
5114 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005115 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005116 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005117 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005118 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005119 return false;
5120 }
Richard Smith3229b742013-05-05 21:17:10 +00005121 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005122}
5123
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005124bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5125 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005126 // Walk through the expression to find the materialized temporary itself.
5127 SmallVector<const Expr *, 2> CommaLHSs;
5128 SmallVector<SubobjectAdjustment, 2> Adjustments;
5129 const Expr *Inner = E->GetTemporaryExpr()->
5130 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005131
Richard Smith84401042013-06-03 05:03:02 +00005132 // If we passed any comma operators, evaluate their LHSs.
5133 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5134 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5135 return false;
5136
Richard Smithe6c01442013-06-05 00:46:14 +00005137 // A materialized temporary with static storage duration can appear within the
5138 // result of a constant expression evaluation, so we need to preserve its
5139 // value for use outside this evaluation.
5140 APValue *Value;
5141 if (E->getStorageDuration() == SD_Static) {
5142 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005143 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005144 Result.set(E);
5145 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005146 Value = &Info.CurrentCall->
5147 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005148 Result.set(E, Info.CurrentCall->Index);
5149 }
5150
Richard Smithea4ad5d2013-06-06 08:19:16 +00005151 QualType Type = Inner->getType();
5152
Richard Smith84401042013-06-03 05:03:02 +00005153 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005154 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5155 (E->getStorageDuration() == SD_Static &&
5156 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5157 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005158 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005159 }
Richard Smith84401042013-06-03 05:03:02 +00005160
5161 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005162 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5163 --I;
5164 switch (Adjustments[I].Kind) {
5165 case SubobjectAdjustment::DerivedToBaseAdjustment:
5166 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5167 Type, Result))
5168 return false;
5169 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5170 break;
5171
5172 case SubobjectAdjustment::FieldAdjustment:
5173 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5174 return false;
5175 Type = Adjustments[I].Field->getType();
5176 break;
5177
5178 case SubobjectAdjustment::MemberPointerAdjustment:
5179 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5180 Adjustments[I].Ptr.RHS))
5181 return false;
5182 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5183 break;
5184 }
5185 }
5186
5187 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005188}
5189
Peter Collingbournee9200682011-05-13 03:29:01 +00005190bool
5191LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005192 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5193 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005194 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5195 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005196 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005197}
5198
Richard Smith6e525142011-12-27 12:18:28 +00005199bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005200 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005201 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005202
Faisal Valie690b7a2016-07-02 22:34:24 +00005203 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005204 << E->getExprOperand()->getType()
5205 << E->getExprOperand()->getSourceRange();
5206 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005207}
5208
Francois Pichet0066db92012-04-16 04:08:35 +00005209bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5210 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005211}
Francois Pichet0066db92012-04-16 04:08:35 +00005212
Peter Collingbournee9200682011-05-13 03:29:01 +00005213bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005214 // Handle static data members.
5215 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005216 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005217 return VisitVarDecl(E, VD);
5218 }
5219
Richard Smith254a73d2011-10-28 22:34:42 +00005220 // Handle static member functions.
5221 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5222 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005223 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005224 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005225 }
5226 }
5227
Richard Smithd62306a2011-11-10 06:34:14 +00005228 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005229 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005230}
5231
Peter Collingbournee9200682011-05-13 03:29:01 +00005232bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005233 // FIXME: Deal with vectors as array subscript bases.
5234 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005235 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005236
George Burgess IVf9013bf2017-02-10 22:52:29 +00005237 if (!evaluatePointer(E->getBase(), Result))
John McCall45d55e42010-05-07 21:00:08 +00005238 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005239
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005240 APSInt Index;
5241 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005242 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005243
Richard Smithd6cc1982017-01-31 02:23:02 +00005244 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005245}
Eli Friedman9a156e52008-11-12 09:44:48 +00005246
Peter Collingbournee9200682011-05-13 03:29:01 +00005247bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005248 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005249}
5250
Richard Smith66c96992012-02-18 22:04:06 +00005251bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5252 if (!Visit(E->getSubExpr()))
5253 return false;
5254 // __real is a no-op on scalar lvalues.
5255 if (E->getSubExpr()->getType()->isAnyComplexType())
5256 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5257 return true;
5258}
5259
5260bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5261 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5262 "lvalue __imag__ on scalar?");
5263 if (!Visit(E->getSubExpr()))
5264 return false;
5265 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5266 return true;
5267}
5268
Richard Smith243ef902013-05-05 23:31:59 +00005269bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005270 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005271 return Error(UO);
5272
5273 if (!this->Visit(UO->getSubExpr()))
5274 return false;
5275
Richard Smith243ef902013-05-05 23:31:59 +00005276 return handleIncDec(
5277 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005278 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005279}
5280
5281bool LValueExprEvaluator::VisitCompoundAssignOperator(
5282 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005283 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005284 return Error(CAO);
5285
Richard Smith3229b742013-05-05 21:17:10 +00005286 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005287
5288 // The overall lvalue result is the result of evaluating the LHS.
5289 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005290 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005291 Evaluate(RHS, this->Info, CAO->getRHS());
5292 return false;
5293 }
5294
Richard Smith3229b742013-05-05 21:17:10 +00005295 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5296 return false;
5297
Richard Smith43e77732013-05-07 04:50:00 +00005298 return handleCompoundAssignment(
5299 this->Info, CAO,
5300 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5301 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005302}
5303
5304bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005305 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005306 return Error(E);
5307
Richard Smith3229b742013-05-05 21:17:10 +00005308 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005309
5310 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005311 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005312 Evaluate(NewVal, this->Info, E->getRHS());
5313 return false;
5314 }
5315
Richard Smith3229b742013-05-05 21:17:10 +00005316 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5317 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005318
5319 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005320 NewVal);
5321}
5322
Eli Friedman9a156e52008-11-12 09:44:48 +00005323//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005324// Pointer Evaluation
5325//===----------------------------------------------------------------------===//
5326
George Burgess IVe3763372016-12-22 02:50:20 +00005327/// \brief Attempts to compute the number of bytes available at the pointer
5328/// returned by a function with the alloc_size attribute. Returns true if we
5329/// were successful. Places an unsigned number into `Result`.
5330///
5331/// This expects the given CallExpr to be a call to a function with an
5332/// alloc_size attribute.
5333static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5334 const CallExpr *Call,
5335 llvm::APInt &Result) {
5336 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5337
5338 // alloc_size args are 1-indexed, 0 means not present.
5339 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5340 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5341 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5342 if (Call->getNumArgs() <= SizeArgNo)
5343 return false;
5344
5345 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5346 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5347 return false;
5348 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5349 return false;
5350 Into = Into.zextOrSelf(BitsInSizeT);
5351 return true;
5352 };
5353
5354 APSInt SizeOfElem;
5355 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5356 return false;
5357
5358 if (!AllocSize->getNumElemsParam()) {
5359 Result = std::move(SizeOfElem);
5360 return true;
5361 }
5362
5363 APSInt NumberOfElems;
5364 // Argument numbers start at 1
5365 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5366 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5367 return false;
5368
5369 bool Overflow;
5370 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5371 if (Overflow)
5372 return false;
5373
5374 Result = std::move(BytesAvailable);
5375 return true;
5376}
5377
5378/// \brief Convenience function. LVal's base must be a call to an alloc_size
5379/// function.
5380static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5381 const LValue &LVal,
5382 llvm::APInt &Result) {
5383 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5384 "Can't get the size of a non alloc_size function");
5385 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5386 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5387 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5388}
5389
5390/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5391/// a function with the alloc_size attribute. If it was possible to do so, this
5392/// function will return true, make Result's Base point to said function call,
5393/// and mark Result's Base as invalid.
5394static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5395 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005396 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005397 return false;
5398
5399 // Because we do no form of static analysis, we only support const variables.
5400 //
5401 // Additionally, we can't support parameters, nor can we support static
5402 // variables (in the latter case, use-before-assign isn't UB; in the former,
5403 // we have no clue what they'll be assigned to).
5404 const auto *VD =
5405 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5406 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5407 return false;
5408
5409 const Expr *Init = VD->getAnyInitializer();
5410 if (!Init)
5411 return false;
5412
5413 const Expr *E = Init->IgnoreParens();
5414 if (!tryUnwrapAllocSizeCall(E))
5415 return false;
5416
5417 // Store E instead of E unwrapped so that the type of the LValue's base is
5418 // what the user wanted.
5419 Result.setInvalid(E);
5420
5421 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5422 Result.addUnsizedArray(Info, Pointee);
5423 return true;
5424}
5425
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005426namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005427class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005428 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005429 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005430 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005431
Peter Collingbournee9200682011-05-13 03:29:01 +00005432 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005433 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005434 return true;
5435 }
George Burgess IVe3763372016-12-22 02:50:20 +00005436
George Burgess IVf9013bf2017-02-10 22:52:29 +00005437 bool evaluateLValue(const Expr *E, LValue &Result) {
5438 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5439 }
5440
5441 bool evaluatePointer(const Expr *E, LValue &Result) {
5442 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5443 }
5444
George Burgess IVe3763372016-12-22 02:50:20 +00005445 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005446public:
Mike Stump11289f42009-09-09 15:08:12 +00005447
George Burgess IVf9013bf2017-02-10 22:52:29 +00005448 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5449 : ExprEvaluatorBaseTy(info), Result(Result),
5450 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005451
Richard Smith2e312c82012-03-03 22:46:17 +00005452 bool Success(const APValue &V, const Expr *E) {
5453 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005454 return true;
5455 }
Richard Smithfddd3842011-12-30 21:15:51 +00005456 bool ZeroInitialization(const Expr *E) {
Yaxun Liu402804b2016-12-15 08:09:08 +00005457 auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
5458 Result.set((Expr*)nullptr, 0, false, true, Offset);
5459 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005460 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005461
John McCall45d55e42010-05-07 21:00:08 +00005462 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005463 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005464 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005465 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005466 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00005467 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005468 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005469 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005470 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005471 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005472 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005473 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005474 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005475 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005476 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005477 }
Richard Smithd62306a2011-11-10 06:34:14 +00005478 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005479 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005480 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005481 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005482 if (!Info.CurrentCall->This) {
5483 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005484 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005485 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005486 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005487 return false;
5488 }
Richard Smithd62306a2011-11-10 06:34:14 +00005489 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005490 // If we are inside a lambda's call operator, the 'this' expression refers
5491 // to the enclosing '*this' object (either by value or reference) which is
5492 // either copied into the closure object's field that represents the '*this'
5493 // or refers to '*this'.
5494 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5495 // Update 'Result' to refer to the data member/field of the closure object
5496 // that represents the '*this' capture.
5497 if (!HandleLValueMember(Info, E, Result,
5498 Info.CurrentCall->LambdaThisCaptureField))
5499 return false;
5500 // If we captured '*this' by reference, replace the field with its referent.
5501 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5502 ->isPointerType()) {
5503 APValue RVal;
5504 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5505 RVal))
5506 return false;
5507
5508 Result.setFrom(Info.Ctx, RVal);
5509 }
5510 }
Richard Smithd62306a2011-11-10 06:34:14 +00005511 return true;
5512 }
John McCallc07a0c72011-02-17 10:25:35 +00005513
Eli Friedman449fe542009-03-23 04:56:01 +00005514 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005515};
Chris Lattner05706e882008-07-11 18:11:29 +00005516} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005517
George Burgess IVf9013bf2017-02-10 22:52:29 +00005518static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5519 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005520 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005521 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005522}
5523
John McCall45d55e42010-05-07 21:00:08 +00005524bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005525 if (E->getOpcode() != BO_Add &&
5526 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005527 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005528
Chris Lattner05706e882008-07-11 18:11:29 +00005529 const Expr *PExp = E->getLHS();
5530 const Expr *IExp = E->getRHS();
5531 if (IExp->getType()->isPointerType())
5532 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005533
George Burgess IVf9013bf2017-02-10 22:52:29 +00005534 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005535 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005536 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005537
John McCall45d55e42010-05-07 21:00:08 +00005538 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005539 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005540 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005541
Richard Smith96e0c102011-11-04 02:25:55 +00005542 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005543 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005544
Ted Kremenek28831752012-08-23 20:46:57 +00005545 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005546 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005547}
Eli Friedman9a156e52008-11-12 09:44:48 +00005548
John McCall45d55e42010-05-07 21:00:08 +00005549bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005550 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005551}
Mike Stump11289f42009-09-09 15:08:12 +00005552
Peter Collingbournee9200682011-05-13 03:29:01 +00005553bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5554 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005555
Eli Friedman847a2bc2009-12-27 05:43:15 +00005556 switch (E->getCastKind()) {
5557 default:
5558 break;
5559
John McCalle3027922010-08-25 11:45:40 +00005560 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005561 case CK_CPointerToObjCPointerCast:
5562 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005563 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005564 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005565 if (!Visit(SubExpr))
5566 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005567 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5568 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5569 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005570 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005571 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005572 if (SubExpr->getType()->isVoidPointerType())
5573 CCEDiag(E, diag::note_constexpr_invalid_cast)
5574 << 3 << SubExpr->getType();
5575 else
5576 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5577 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005578 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5579 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005580 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005581
Anders Carlsson18275092010-10-31 20:41:46 +00005582 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005583 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005584 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005585 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005586 if (!Result.Base && Result.Offset.isZero())
5587 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005588
Richard Smithd62306a2011-11-10 06:34:14 +00005589 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005590 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005591 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5592 castAs<PointerType>()->getPointeeType(),
5593 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005594
Richard Smith027bf112011-11-17 22:56:20 +00005595 case CK_BaseToDerived:
5596 if (!Visit(E->getSubExpr()))
5597 return false;
5598 if (!Result.Base && Result.Offset.isZero())
5599 return true;
5600 return HandleBaseToDerivedCast(Info, E, Result);
5601
Richard Smith0b0a0b62011-10-29 20:57:55 +00005602 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005603 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005604 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005605
John McCalle3027922010-08-25 11:45:40 +00005606 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005607 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5608
Richard Smith2e312c82012-03-03 22:46:17 +00005609 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005610 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005611 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005612
John McCall45d55e42010-05-07 21:00:08 +00005613 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005614 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5615 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005616 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005617 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005618 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005619 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005620 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005621 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005622 return true;
5623 } else {
5624 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005625 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005626 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005627 }
5628 }
John McCalle3027922010-08-25 11:45:40 +00005629 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005630 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005631 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005632 return false;
5633 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005634 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005635 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005636 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005637 return false;
5638 }
Richard Smith96e0c102011-11-04 02:25:55 +00005639 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005640 if (const ConstantArrayType *CAT
5641 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5642 Result.addArray(Info, E, CAT);
5643 else
5644 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005645 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005646
John McCalle3027922010-08-25 11:45:40 +00005647 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005648 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005649
5650 case CK_LValueToRValue: {
5651 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005652 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005653 return false;
5654
5655 APValue RVal;
5656 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5657 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5658 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005659 return InvalidBaseOK &&
5660 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005661 return Success(RVal, E);
5662 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005663 }
5664
Richard Smith11562c52011-10-28 17:51:58 +00005665 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005666}
Chris Lattner05706e882008-07-11 18:11:29 +00005667
Hal Finkel0dd05d42014-10-03 17:18:37 +00005668static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5669 // C++ [expr.alignof]p3:
5670 // When alignof is applied to a reference type, the result is the
5671 // alignment of the referenced type.
5672 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5673 T = Ref->getPointeeType();
5674
5675 // __alignof is defined to return the preferred alignment.
5676 return Info.Ctx.toCharUnitsFromBits(
5677 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5678}
5679
5680static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5681 E = E->IgnoreParens();
5682
5683 // The kinds of expressions that we have special-case logic here for
5684 // should be kept up to date with the special checks for those
5685 // expressions in Sema.
5686
5687 // alignof decl is always accepted, even if it doesn't make sense: we default
5688 // to 1 in those cases.
5689 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5690 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5691 /*RefAsPointee*/true);
5692
5693 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5694 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5695 /*RefAsPointee*/true);
5696
5697 return GetAlignOfType(Info, E->getType());
5698}
5699
George Burgess IVe3763372016-12-22 02:50:20 +00005700// To be clear: this happily visits unsupported builtins. Better name welcomed.
5701bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5702 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5703 return true;
5704
George Burgess IVf9013bf2017-02-10 22:52:29 +00005705 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005706 return false;
5707
5708 Result.setInvalid(E);
5709 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5710 Result.addUnsizedArray(Info, PointeeTy);
5711 return true;
5712}
5713
Peter Collingbournee9200682011-05-13 03:29:01 +00005714bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005715 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005716 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005717
Richard Smith6328cbd2016-11-16 00:57:23 +00005718 if (unsigned BuiltinOp = E->getBuiltinCallee())
5719 return VisitBuiltinCallExpr(E, BuiltinOp);
5720
George Burgess IVe3763372016-12-22 02:50:20 +00005721 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005722}
5723
5724bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5725 unsigned BuiltinOp) {
5726 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005727 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005728 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005729 case Builtin::BI__builtin_assume_aligned: {
5730 // We need to be very careful here because: if the pointer does not have the
5731 // asserted alignment, then the behavior is undefined, and undefined
5732 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005733 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005734 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005735
Hal Finkel0dd05d42014-10-03 17:18:37 +00005736 LValue OffsetResult(Result);
5737 APSInt Alignment;
5738 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5739 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005740 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005741
5742 if (E->getNumArgs() > 2) {
5743 APSInt Offset;
5744 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5745 return false;
5746
Richard Smith642a2362017-01-30 23:30:26 +00005747 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005748 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5749 }
5750
5751 // If there is a base object, then it must have the correct alignment.
5752 if (OffsetResult.Base) {
5753 CharUnits BaseAlignment;
5754 if (const ValueDecl *VD =
5755 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5756 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5757 } else {
5758 BaseAlignment =
5759 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5760 }
5761
5762 if (BaseAlignment < Align) {
5763 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005764 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005765 CCEDiag(E->getArg(0),
5766 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005767 << (unsigned)BaseAlignment.getQuantity()
5768 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005769 return false;
5770 }
5771 }
5772
5773 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005774 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005775 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005776
Richard Smith642a2362017-01-30 23:30:26 +00005777 (OffsetResult.Base
5778 ? CCEDiag(E->getArg(0),
5779 diag::note_constexpr_baa_insufficient_alignment) << 1
5780 : CCEDiag(E->getArg(0),
5781 diag::note_constexpr_baa_value_insufficient_alignment))
5782 << (int)OffsetResult.Offset.getQuantity()
5783 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005784 return false;
5785 }
5786
5787 return true;
5788 }
Richard Smithe9507952016-11-12 01:39:56 +00005789
5790 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005791 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005792 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005793 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005794 if (Info.getLangOpts().CPlusPlus11)
5795 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5796 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005797 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005798 else
5799 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5800 // Fall through.
5801 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005802 case Builtin::BI__builtin_wcschr:
5803 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005804 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005805 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005806 if (!Visit(E->getArg(0)))
5807 return false;
5808 APSInt Desired;
5809 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5810 return false;
5811 uint64_t MaxLength = uint64_t(-1);
5812 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005813 BuiltinOp != Builtin::BIwcschr &&
5814 BuiltinOp != Builtin::BI__builtin_strchr &&
5815 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005816 APSInt N;
5817 if (!EvaluateInteger(E->getArg(2), N, Info))
5818 return false;
5819 MaxLength = N.getExtValue();
5820 }
5821
Richard Smith8110c9d2016-11-29 19:45:17 +00005822 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005823
Richard Smith8110c9d2016-11-29 19:45:17 +00005824 // Figure out what value we're actually looking for (after converting to
5825 // the corresponding unsigned type if necessary).
5826 uint64_t DesiredVal;
5827 bool StopAtNull = false;
5828 switch (BuiltinOp) {
5829 case Builtin::BIstrchr:
5830 case Builtin::BI__builtin_strchr:
5831 // strchr compares directly to the passed integer, and therefore
5832 // always fails if given an int that is not a char.
5833 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5834 E->getArg(1)->getType(),
5835 Desired),
5836 Desired))
5837 return ZeroInitialization(E);
5838 StopAtNull = true;
5839 // Fall through.
5840 case Builtin::BImemchr:
5841 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005842 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005843 // memchr compares by converting both sides to unsigned char. That's also
5844 // correct for strchr if we get this far (to cope with plain char being
5845 // unsigned in the strchr case).
5846 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5847 break;
Richard Smithe9507952016-11-12 01:39:56 +00005848
Richard Smith8110c9d2016-11-29 19:45:17 +00005849 case Builtin::BIwcschr:
5850 case Builtin::BI__builtin_wcschr:
5851 StopAtNull = true;
5852 // Fall through.
5853 case Builtin::BIwmemchr:
5854 case Builtin::BI__builtin_wmemchr:
5855 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5856 DesiredVal = Desired.getZExtValue();
5857 break;
5858 }
Richard Smithe9507952016-11-12 01:39:56 +00005859
5860 for (; MaxLength; --MaxLength) {
5861 APValue Char;
5862 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5863 !Char.isInt())
5864 return false;
5865 if (Char.getInt().getZExtValue() == DesiredVal)
5866 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005867 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005868 break;
5869 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5870 return false;
5871 }
5872 // Not found: return nullptr.
5873 return ZeroInitialization(E);
5874 }
5875
Richard Smith6cbd65d2013-07-11 02:27:57 +00005876 default:
George Burgess IVe3763372016-12-22 02:50:20 +00005877 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005878 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005879}
Chris Lattner05706e882008-07-11 18:11:29 +00005880
5881//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005882// Member Pointer Evaluation
5883//===----------------------------------------------------------------------===//
5884
5885namespace {
5886class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005887 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005888 MemberPtr &Result;
5889
5890 bool Success(const ValueDecl *D) {
5891 Result = MemberPtr(D);
5892 return true;
5893 }
5894public:
5895
5896 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5897 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5898
Richard Smith2e312c82012-03-03 22:46:17 +00005899 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005900 Result.setFrom(V);
5901 return true;
5902 }
Richard Smithfddd3842011-12-30 21:15:51 +00005903 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005904 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005905 }
5906
5907 bool VisitCastExpr(const CastExpr *E);
5908 bool VisitUnaryAddrOf(const UnaryOperator *E);
5909};
5910} // end anonymous namespace
5911
5912static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5913 EvalInfo &Info) {
5914 assert(E->isRValue() && E->getType()->isMemberPointerType());
5915 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5916}
5917
5918bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5919 switch (E->getCastKind()) {
5920 default:
5921 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5922
5923 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005924 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005925 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005926
5927 case CK_BaseToDerivedMemberPointer: {
5928 if (!Visit(E->getSubExpr()))
5929 return false;
5930 if (E->path_empty())
5931 return true;
5932 // Base-to-derived member pointer casts store the path in derived-to-base
5933 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5934 // the wrong end of the derived->base arc, so stagger the path by one class.
5935 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5936 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5937 PathI != PathE; ++PathI) {
5938 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5939 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5940 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005941 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005942 }
5943 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5944 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005945 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005946 return true;
5947 }
5948
5949 case CK_DerivedToBaseMemberPointer:
5950 if (!Visit(E->getSubExpr()))
5951 return false;
5952 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5953 PathE = E->path_end(); PathI != PathE; ++PathI) {
5954 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5955 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5956 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005957 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005958 }
5959 return true;
5960 }
5961}
5962
5963bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5964 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5965 // member can be formed.
5966 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5967}
5968
5969//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005970// Record Evaluation
5971//===----------------------------------------------------------------------===//
5972
5973namespace {
5974 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005975 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005976 const LValue &This;
5977 APValue &Result;
5978 public:
5979
5980 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5981 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5982
Richard Smith2e312c82012-03-03 22:46:17 +00005983 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005984 Result = V;
5985 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005986 }
Richard Smithb8348f52016-05-12 22:16:28 +00005987 bool ZeroInitialization(const Expr *E) {
5988 return ZeroInitialization(E, E->getType());
5989 }
5990 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005991
Richard Smith52a980a2015-08-28 02:43:42 +00005992 bool VisitCallExpr(const CallExpr *E) {
5993 return handleCallExpr(E, Result, &This);
5994 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005995 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005996 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005997 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5998 return VisitCXXConstructExpr(E, E->getType());
5999 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006000 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006001 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006002 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006003 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006004 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006005}
Richard Smithd62306a2011-11-10 06:34:14 +00006006
Richard Smithfddd3842011-12-30 21:15:51 +00006007/// Perform zero-initialization on an object of non-union class type.
6008/// C++11 [dcl.init]p5:
6009/// To zero-initialize an object or reference of type T means:
6010/// [...]
6011/// -- if T is a (possibly cv-qualified) non-union class type,
6012/// each non-static data member and each base-class subobject is
6013/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006014static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6015 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006016 const LValue &This, APValue &Result) {
6017 assert(!RD->isUnion() && "Expected non-union class type");
6018 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6019 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006020 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006021
John McCalld7bca762012-05-01 00:38:49 +00006022 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006023 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6024
6025 if (CD) {
6026 unsigned Index = 0;
6027 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006028 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006029 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6030 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006031 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6032 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006033 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006034 Result.getStructBase(Index)))
6035 return false;
6036 }
6037 }
6038
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006039 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006040 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006041 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006042 continue;
6043
6044 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006045 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006046 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006047
David Blaikie2d7c57e2012-04-30 02:36:29 +00006048 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006049 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006050 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006051 return false;
6052 }
6053
6054 return true;
6055}
6056
Richard Smithb8348f52016-05-12 22:16:28 +00006057bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6058 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006059 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006060 if (RD->isUnion()) {
6061 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6062 // object's first non-static named data member is zero-initialized
6063 RecordDecl::field_iterator I = RD->field_begin();
6064 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006065 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006066 return true;
6067 }
6068
6069 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006070 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006071 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006072 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006073 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006074 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006075 }
6076
Richard Smith5d108602012-02-17 00:44:16 +00006077 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006078 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006079 return false;
6080 }
6081
Richard Smitha8105bc2012-01-06 16:39:00 +00006082 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006083}
6084
Richard Smithe97cbd72011-11-11 04:05:33 +00006085bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6086 switch (E->getCastKind()) {
6087 default:
6088 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6089
6090 case CK_ConstructorConversion:
6091 return Visit(E->getSubExpr());
6092
6093 case CK_DerivedToBase:
6094 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006095 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006096 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006097 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006098 if (!DerivedObject.isStruct())
6099 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006100
6101 // Derived-to-base rvalue conversion: just slice off the derived part.
6102 APValue *Value = &DerivedObject;
6103 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6104 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6105 PathE = E->path_end(); PathI != PathE; ++PathI) {
6106 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6107 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6108 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6109 RD = Base;
6110 }
6111 Result = *Value;
6112 return true;
6113 }
6114 }
6115}
6116
Richard Smithd62306a2011-11-10 06:34:14 +00006117bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006118 if (E->isTransparent())
6119 return Visit(E->getInit(0));
6120
Richard Smithd62306a2011-11-10 06:34:14 +00006121 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006122 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006123 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6124
6125 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006126 const FieldDecl *Field = E->getInitializedFieldInUnion();
6127 Result = APValue(Field);
6128 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006129 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006130
6131 // If the initializer list for a union does not contain any elements, the
6132 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006133 // FIXME: The element should be initialized from an initializer list.
6134 // Is this difference ever observable for initializer lists which
6135 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006136 ImplicitValueInitExpr VIE(Field->getType());
6137 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6138
Richard Smithd62306a2011-11-10 06:34:14 +00006139 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006140 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6141 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006142
6143 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6144 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6145 isa<CXXDefaultInitExpr>(InitExpr));
6146
Richard Smithb228a862012-02-15 02:18:13 +00006147 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006148 }
6149
Richard Smith872307e2016-03-08 22:17:41 +00006150 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006151 if (Result.isUninit())
6152 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6153 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006154 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006155 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006156
6157 // Initialize base classes.
6158 if (CXXRD) {
6159 for (const auto &Base : CXXRD->bases()) {
6160 assert(ElementNo < E->getNumInits() && "missing init for base class");
6161 const Expr *Init = E->getInit(ElementNo);
6162
6163 LValue Subobject = This;
6164 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6165 return false;
6166
6167 APValue &FieldVal = Result.getStructBase(ElementNo);
6168 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006169 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006170 return false;
6171 Success = false;
6172 }
6173 ++ElementNo;
6174 }
6175 }
6176
6177 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006178 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006179 // Anonymous bit-fields are not considered members of the class for
6180 // purposes of aggregate initialization.
6181 if (Field->isUnnamedBitfield())
6182 continue;
6183
6184 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006185
Richard Smith253c2a32012-01-27 01:14:48 +00006186 bool HaveInit = ElementNo < E->getNumInits();
6187
6188 // FIXME: Diagnostics here should point to the end of the initializer
6189 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006190 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006191 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006192 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006193
6194 // Perform an implicit value-initialization for members beyond the end of
6195 // the initializer list.
6196 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006197 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006198
Richard Smith852c9db2013-04-20 22:23:05 +00006199 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6200 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6201 isa<CXXDefaultInitExpr>(Init));
6202
Richard Smith49ca8aa2013-08-06 07:09:20 +00006203 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6204 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6205 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006206 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006207 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006208 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006209 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006210 }
6211 }
6212
Richard Smith253c2a32012-01-27 01:14:48 +00006213 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006214}
6215
Richard Smithb8348f52016-05-12 22:16:28 +00006216bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6217 QualType T) {
6218 // Note that E's type is not necessarily the type of our class here; we might
6219 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006220 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006221 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6222
Richard Smithfddd3842011-12-30 21:15:51 +00006223 bool ZeroInit = E->requiresZeroInitialization();
6224 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006225 // If we've already performed zero-initialization, we're already done.
6226 if (!Result.isUninit())
6227 return true;
6228
Richard Smithda3f4fd2014-03-05 23:32:50 +00006229 // We can get here in two different ways:
6230 // 1) We're performing value-initialization, and should zero-initialize
6231 // the object, or
6232 // 2) We're performing default-initialization of an object with a trivial
6233 // constexpr default constructor, in which case we should start the
6234 // lifetimes of all the base subobjects (there can be no data member
6235 // subobjects in this case) per [basic.life]p1.
6236 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006237 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006238 }
6239
Craig Topper36250ad2014-05-12 05:36:57 +00006240 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006241 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006242
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006243 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006244 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006245
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006246 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006247 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006248 if (const MaterializeTemporaryExpr *ME
6249 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6250 return Visit(ME->GetTemporaryExpr());
6251
Richard Smithb8348f52016-05-12 22:16:28 +00006252 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006253 return false;
6254
Craig Topper5fc8fc22014-08-27 06:28:36 +00006255 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006256 return HandleConstructorCall(E, This, Args,
6257 cast<CXXConstructorDecl>(Definition), Info,
6258 Result);
6259}
6260
6261bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6262 const CXXInheritedCtorInitExpr *E) {
6263 if (!Info.CurrentCall) {
6264 assert(Info.checkingPotentialConstantExpression());
6265 return false;
6266 }
6267
6268 const CXXConstructorDecl *FD = E->getConstructor();
6269 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6270 return false;
6271
6272 const FunctionDecl *Definition = nullptr;
6273 auto Body = FD->getBody(Definition);
6274
6275 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6276 return false;
6277
6278 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006279 cast<CXXConstructorDecl>(Definition), Info,
6280 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006281}
6282
Richard Smithcc1b96d2013-06-12 22:31:48 +00006283bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6284 const CXXStdInitializerListExpr *E) {
6285 const ConstantArrayType *ArrayType =
6286 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6287
6288 LValue Array;
6289 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6290 return false;
6291
6292 // Get a pointer to the first element of the array.
6293 Array.addArray(Info, E, ArrayType);
6294
6295 // FIXME: Perform the checks on the field types in SemaInit.
6296 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6297 RecordDecl::field_iterator Field = Record->field_begin();
6298 if (Field == Record->field_end())
6299 return Error(E);
6300
6301 // Start pointer.
6302 if (!Field->getType()->isPointerType() ||
6303 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6304 ArrayType->getElementType()))
6305 return Error(E);
6306
6307 // FIXME: What if the initializer_list type has base classes, etc?
6308 Result = APValue(APValue::UninitStruct(), 0, 2);
6309 Array.moveInto(Result.getStructField(0));
6310
6311 if (++Field == Record->field_end())
6312 return Error(E);
6313
6314 if (Field->getType()->isPointerType() &&
6315 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6316 ArrayType->getElementType())) {
6317 // End pointer.
6318 if (!HandleLValueArrayAdjustment(Info, E, Array,
6319 ArrayType->getElementType(),
6320 ArrayType->getSize().getZExtValue()))
6321 return false;
6322 Array.moveInto(Result.getStructField(1));
6323 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6324 // Length.
6325 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6326 else
6327 return Error(E);
6328
6329 if (++Field != Record->field_end())
6330 return Error(E);
6331
6332 return true;
6333}
6334
Faisal Valic72a08c2017-01-09 03:02:53 +00006335bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6336 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6337 if (ClosureClass->isInvalidDecl()) return false;
6338
6339 if (Info.checkingPotentialConstantExpression()) return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00006340
6341 const size_t NumFields =
6342 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006343
6344 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6345 E->capture_init_end()) &&
6346 "The number of lambda capture initializers should equal the number of "
6347 "fields within the closure type");
6348
Faisal Vali051e3a22017-02-16 04:12:21 +00006349 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6350 // Iterate through all the lambda's closure object's fields and initialize
6351 // them.
6352 auto *CaptureInitIt = E->capture_init_begin();
6353 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6354 bool Success = true;
6355 for (const auto *Field : ClosureClass->fields()) {
6356 assert(CaptureInitIt != E->capture_init_end());
6357 // Get the initializer for this field
6358 Expr *const CurFieldInit = *CaptureInitIt++;
6359
6360 // If there is no initializer, either this is a VLA or an error has
6361 // occurred.
6362 if (!CurFieldInit)
6363 return Error(E);
6364
6365 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6366 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6367 if (!Info.keepEvaluatingAfterFailure())
6368 return false;
6369 Success = false;
6370 }
6371 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006372 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006373 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006374}
6375
Richard Smithd62306a2011-11-10 06:34:14 +00006376static bool EvaluateRecord(const Expr *E, const LValue &This,
6377 APValue &Result, EvalInfo &Info) {
6378 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006379 "can't evaluate expression as a record rvalue");
6380 return RecordExprEvaluator(Info, This, Result).Visit(E);
6381}
6382
6383//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006384// Temporary Evaluation
6385//
6386// Temporaries are represented in the AST as rvalues, but generally behave like
6387// lvalues. The full-object of which the temporary is a subobject is implicitly
6388// materialized so that a reference can bind to it.
6389//===----------------------------------------------------------------------===//
6390namespace {
6391class TemporaryExprEvaluator
6392 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6393public:
6394 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006395 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006396
6397 /// Visit an expression which constructs the value of this temporary.
6398 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006399 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006400 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6401 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006402 }
6403
6404 bool VisitCastExpr(const CastExpr *E) {
6405 switch (E->getCastKind()) {
6406 default:
6407 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6408
6409 case CK_ConstructorConversion:
6410 return VisitConstructExpr(E->getSubExpr());
6411 }
6412 }
6413 bool VisitInitListExpr(const InitListExpr *E) {
6414 return VisitConstructExpr(E);
6415 }
6416 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6417 return VisitConstructExpr(E);
6418 }
6419 bool VisitCallExpr(const CallExpr *E) {
6420 return VisitConstructExpr(E);
6421 }
Richard Smith513955c2014-12-17 19:24:30 +00006422 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6423 return VisitConstructExpr(E);
6424 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006425 bool VisitLambdaExpr(const LambdaExpr *E) {
6426 return VisitConstructExpr(E);
6427 }
Richard Smith027bf112011-11-17 22:56:20 +00006428};
6429} // end anonymous namespace
6430
6431/// Evaluate an expression of record type as a temporary.
6432static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006433 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006434 return TemporaryExprEvaluator(Info, Result).Visit(E);
6435}
6436
6437//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006438// Vector Evaluation
6439//===----------------------------------------------------------------------===//
6440
6441namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006442 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006443 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006444 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006445 public:
Mike Stump11289f42009-09-09 15:08:12 +00006446
Richard Smith2d406342011-10-22 21:10:00 +00006447 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6448 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006449
Craig Topper9798b932015-09-29 04:30:05 +00006450 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006451 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6452 // FIXME: remove this APValue copy.
6453 Result = APValue(V.data(), V.size());
6454 return true;
6455 }
Richard Smith2e312c82012-03-03 22:46:17 +00006456 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006457 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006458 Result = V;
6459 return true;
6460 }
Richard Smithfddd3842011-12-30 21:15:51 +00006461 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006462
Richard Smith2d406342011-10-22 21:10:00 +00006463 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006464 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006465 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006466 bool VisitInitListExpr(const InitListExpr *E);
6467 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006468 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006469 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006470 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006471 };
6472} // end anonymous namespace
6473
6474static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006475 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006476 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006477}
6478
George Burgess IV533ff002015-12-11 00:23:35 +00006479bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006480 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006481 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006482
Richard Smith161f09a2011-12-06 22:44:34 +00006483 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006484 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006485
Eli Friedmanc757de22011-03-25 00:43:55 +00006486 switch (E->getCastKind()) {
6487 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006488 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006489 if (SETy->isIntegerType()) {
6490 APSInt IntResult;
6491 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006492 return false;
6493 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006494 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006495 APFloat FloatResult(0.0);
6496 if (!EvaluateFloat(SE, FloatResult, Info))
6497 return false;
6498 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006499 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006500 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006501 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006502
6503 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006504 SmallVector<APValue, 4> Elts(NElts, Val);
6505 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006506 }
Eli Friedman803acb32011-12-22 03:51:45 +00006507 case CK_BitCast: {
6508 // Evaluate the operand into an APInt we can extract from.
6509 llvm::APInt SValInt;
6510 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6511 return false;
6512 // Extract the elements
6513 QualType EltTy = VTy->getElementType();
6514 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6515 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6516 SmallVector<APValue, 4> Elts;
6517 if (EltTy->isRealFloatingType()) {
6518 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006519 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006520 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006521 FloatEltSize = 80;
6522 for (unsigned i = 0; i < NElts; i++) {
6523 llvm::APInt Elt;
6524 if (BigEndian)
6525 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6526 else
6527 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006528 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006529 }
6530 } else if (EltTy->isIntegerType()) {
6531 for (unsigned i = 0; i < NElts; i++) {
6532 llvm::APInt Elt;
6533 if (BigEndian)
6534 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6535 else
6536 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6537 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6538 }
6539 } else {
6540 return Error(E);
6541 }
6542 return Success(Elts, E);
6543 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006544 default:
Richard Smith11562c52011-10-28 17:51:58 +00006545 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006546 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006547}
6548
Richard Smith2d406342011-10-22 21:10:00 +00006549bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006550VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006551 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006552 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006553 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006554
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006555 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006556 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006557
Eli Friedmanb9c71292012-01-03 23:24:20 +00006558 // The number of initializers can be less than the number of
6559 // vector elements. For OpenCL, this can be due to nested vector
6560 // initialization. For GCC compatibility, missing trailing elements
6561 // should be initialized with zeroes.
6562 unsigned CountInits = 0, CountElts = 0;
6563 while (CountElts < NumElements) {
6564 // Handle nested vector initialization.
6565 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006566 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006567 APValue v;
6568 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6569 return Error(E);
6570 unsigned vlen = v.getVectorLength();
6571 for (unsigned j = 0; j < vlen; j++)
6572 Elements.push_back(v.getVectorElt(j));
6573 CountElts += vlen;
6574 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006575 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006576 if (CountInits < NumInits) {
6577 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006578 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006579 } else // trailing integer zero.
6580 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6581 Elements.push_back(APValue(sInt));
6582 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006583 } else {
6584 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006585 if (CountInits < NumInits) {
6586 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006587 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006588 } else // trailing float zero.
6589 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6590 Elements.push_back(APValue(f));
6591 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006592 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006593 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006594 }
Richard Smith2d406342011-10-22 21:10:00 +00006595 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006596}
6597
Richard Smith2d406342011-10-22 21:10:00 +00006598bool
Richard Smithfddd3842011-12-30 21:15:51 +00006599VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006600 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006601 QualType EltTy = VT->getElementType();
6602 APValue ZeroElement;
6603 if (EltTy->isIntegerType())
6604 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6605 else
6606 ZeroElement =
6607 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6608
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006609 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006610 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006611}
6612
Richard Smith2d406342011-10-22 21:10:00 +00006613bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006614 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006615 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006616}
6617
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006618//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006619// Array Evaluation
6620//===----------------------------------------------------------------------===//
6621
6622namespace {
6623 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006624 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006625 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006626 APValue &Result;
6627 public:
6628
Richard Smithd62306a2011-11-10 06:34:14 +00006629 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6630 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006631
6632 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006633 assert((V.isArray() || V.isLValue()) &&
6634 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006635 Result = V;
6636 return true;
6637 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006638
Richard Smithfddd3842011-12-30 21:15:51 +00006639 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006640 const ConstantArrayType *CAT =
6641 Info.Ctx.getAsConstantArrayType(E->getType());
6642 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006643 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006644
6645 Result = APValue(APValue::UninitArray(), 0,
6646 CAT->getSize().getZExtValue());
6647 if (!Result.hasArrayFiller()) return true;
6648
Richard Smithfddd3842011-12-30 21:15:51 +00006649 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006650 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006651 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006652 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006653 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006654 }
6655
Richard Smith52a980a2015-08-28 02:43:42 +00006656 bool VisitCallExpr(const CallExpr *E) {
6657 return handleCallExpr(E, Result, &This);
6658 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006659 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006660 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006661 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006662 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6663 const LValue &Subobject,
6664 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006665 };
6666} // end anonymous namespace
6667
Richard Smithd62306a2011-11-10 06:34:14 +00006668static bool EvaluateArray(const Expr *E, const LValue &This,
6669 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006670 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006671 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006672}
6673
6674bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6675 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6676 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006677 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006678
Richard Smithca2cfbf2011-12-22 01:07:19 +00006679 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6680 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006681 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006682 LValue LV;
6683 if (!EvaluateLValue(E->getInit(0), LV, Info))
6684 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006685 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006686 LV.moveInto(Val);
6687 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006688 }
6689
Richard Smith253c2a32012-01-27 01:14:48 +00006690 bool Success = true;
6691
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006692 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6693 "zero-initialized array shouldn't have any initialized elts");
6694 APValue Filler;
6695 if (Result.isArray() && Result.hasArrayFiller())
6696 Filler = Result.getArrayFiller();
6697
Richard Smith9543c5e2013-04-22 14:44:29 +00006698 unsigned NumEltsToInit = E->getNumInits();
6699 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006700 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006701
6702 // If the initializer might depend on the array index, run it for each
6703 // array element. For now, just whitelist non-class value-initialization.
6704 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6705 NumEltsToInit = NumElts;
6706
6707 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006708
6709 // If the array was previously zero-initialized, preserve the
6710 // zero-initialized values.
6711 if (!Filler.isUninit()) {
6712 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6713 Result.getArrayInitializedElt(I) = Filler;
6714 if (Result.hasArrayFiller())
6715 Result.getArrayFiller() = Filler;
6716 }
6717
Richard Smithd62306a2011-11-10 06:34:14 +00006718 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006719 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006720 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6721 const Expr *Init =
6722 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006723 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006724 Info, Subobject, Init) ||
6725 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006726 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006727 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006728 return false;
6729 Success = false;
6730 }
Richard Smithd62306a2011-11-10 06:34:14 +00006731 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006732
Richard Smith9543c5e2013-04-22 14:44:29 +00006733 if (!Result.hasArrayFiller())
6734 return Success;
6735
6736 // If we get here, we have a trivial filler, which we can just evaluate
6737 // once and splat over the rest of the array elements.
6738 assert(FillerExpr && "no array filler for incomplete init list");
6739 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6740 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006741}
6742
Richard Smith410306b2016-12-12 02:53:20 +00006743bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6744 if (E->getCommonExpr() &&
6745 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6746 Info, E->getCommonExpr()->getSourceExpr()))
6747 return false;
6748
6749 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6750
6751 uint64_t Elements = CAT->getSize().getZExtValue();
6752 Result = APValue(APValue::UninitArray(), Elements, Elements);
6753
6754 LValue Subobject = This;
6755 Subobject.addArray(Info, E, CAT);
6756
6757 bool Success = true;
6758 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6759 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6760 Info, Subobject, E->getSubExpr()) ||
6761 !HandleLValueArrayAdjustment(Info, E, Subobject,
6762 CAT->getElementType(), 1)) {
6763 if (!Info.noteFailure())
6764 return false;
6765 Success = false;
6766 }
6767 }
6768
6769 return Success;
6770}
6771
Richard Smith027bf112011-11-17 22:56:20 +00006772bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006773 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6774}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006775
Richard Smith9543c5e2013-04-22 14:44:29 +00006776bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6777 const LValue &Subobject,
6778 APValue *Value,
6779 QualType Type) {
6780 bool HadZeroInit = !Value->isUninit();
6781
6782 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6783 unsigned N = CAT->getSize().getZExtValue();
6784
6785 // Preserve the array filler if we had prior zero-initialization.
6786 APValue Filler =
6787 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6788 : APValue();
6789
6790 *Value = APValue(APValue::UninitArray(), N, N);
6791
6792 if (HadZeroInit)
6793 for (unsigned I = 0; I != N; ++I)
6794 Value->getArrayInitializedElt(I) = Filler;
6795
6796 // Initialize the elements.
6797 LValue ArrayElt = Subobject;
6798 ArrayElt.addArray(Info, E, CAT);
6799 for (unsigned I = 0; I != N; ++I)
6800 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6801 CAT->getElementType()) ||
6802 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6803 CAT->getElementType(), 1))
6804 return false;
6805
6806 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006807 }
Richard Smith027bf112011-11-17 22:56:20 +00006808
Richard Smith9543c5e2013-04-22 14:44:29 +00006809 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006810 return Error(E);
6811
Richard Smithb8348f52016-05-12 22:16:28 +00006812 return RecordExprEvaluator(Info, Subobject, *Value)
6813 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006814}
6815
Richard Smithf3e9e432011-11-07 09:22:26 +00006816//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006817// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006818//
6819// As a GNU extension, we support casting pointers to sufficiently-wide integer
6820// types and back in constant folding. Integer values are thus represented
6821// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006822//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006823
6824namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006825class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006826 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006827 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006828public:
Richard Smith2e312c82012-03-03 22:46:17 +00006829 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006830 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006831
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006832 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006833 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006834 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006835 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006836 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006837 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006838 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006839 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006840 return true;
6841 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006842 bool Success(const llvm::APSInt &SI, const Expr *E) {
6843 return Success(SI, E, Result);
6844 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006845
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006846 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006847 assert(E->getType()->isIntegralOrEnumerationType() &&
6848 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006849 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006850 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006851 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006852 Result.getInt().setIsUnsigned(
6853 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006854 return true;
6855 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006856 bool Success(const llvm::APInt &I, const Expr *E) {
6857 return Success(I, E, Result);
6858 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006859
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006860 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006861 assert(E->getType()->isIntegralOrEnumerationType() &&
6862 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006863 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006864 return true;
6865 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006866 bool Success(uint64_t Value, const Expr *E) {
6867 return Success(Value, E, Result);
6868 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006869
Ken Dyckdbc01912011-03-11 02:13:43 +00006870 bool Success(CharUnits Size, const Expr *E) {
6871 return Success(Size.getQuantity(), E);
6872 }
6873
Richard Smith2e312c82012-03-03 22:46:17 +00006874 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006875 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006876 Result = V;
6877 return true;
6878 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006879 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006880 }
Mike Stump11289f42009-09-09 15:08:12 +00006881
Richard Smithfddd3842011-12-30 21:15:51 +00006882 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006883
Peter Collingbournee9200682011-05-13 03:29:01 +00006884 //===--------------------------------------------------------------------===//
6885 // Visitor Methods
6886 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006887
Chris Lattner7174bf32008-07-12 00:38:25 +00006888 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006889 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006890 }
6891 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006892 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006893 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006894
6895 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6896 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006897 if (CheckReferencedDecl(E, E->getDecl()))
6898 return true;
6899
6900 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006901 }
6902 bool VisitMemberExpr(const MemberExpr *E) {
6903 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006904 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006905 return true;
6906 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006907
6908 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006909 }
6910
Peter Collingbournee9200682011-05-13 03:29:01 +00006911 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006912 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006913 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006914 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006915 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006916
Peter Collingbournee9200682011-05-13 03:29:01 +00006917 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006918 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006919
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006920 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006921 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006922 }
Mike Stump11289f42009-09-09 15:08:12 +00006923
Ted Kremeneke65b0862012-03-06 20:05:56 +00006924 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6925 return Success(E->getValue(), E);
6926 }
Richard Smith410306b2016-12-12 02:53:20 +00006927
6928 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6929 if (Info.ArrayInitIndex == uint64_t(-1)) {
6930 // We were asked to evaluate this subexpression independent of the
6931 // enclosing ArrayInitLoopExpr. We can't do that.
6932 Info.FFDiag(E);
6933 return false;
6934 }
6935 return Success(Info.ArrayInitIndex, E);
6936 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00006937
Richard Smith4ce706a2011-10-11 21:43:33 +00006938 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006939 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006940 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006941 }
6942
Douglas Gregor29c42f22012-02-24 07:38:34 +00006943 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6944 return Success(E->getValue(), E);
6945 }
6946
John Wiegley6242b6a2011-04-28 00:16:57 +00006947 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6948 return Success(E->getValue(), E);
6949 }
6950
John Wiegleyf9f65842011-04-25 06:54:41 +00006951 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6952 return Success(E->getValue(), E);
6953 }
6954
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006955 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006956 bool VisitUnaryImag(const UnaryOperator *E);
6957
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006958 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006959 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006960
Eli Friedman4e7a2412009-02-27 04:45:43 +00006961 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006962};
Chris Lattner05706e882008-07-11 18:11:29 +00006963} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006964
Richard Smith11562c52011-10-28 17:51:58 +00006965/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6966/// produce either the integer value or a pointer.
6967///
6968/// GCC has a heinous extension which folds casts between pointer types and
6969/// pointer-sized integral types. We support this by allowing the evaluation of
6970/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6971/// Some simple arithmetic on such values is supported (they are treated much
6972/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006973static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006974 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006975 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006976 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006977}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006978
Richard Smithf57d8cb2011-12-09 22:58:01 +00006979static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006980 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006981 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006982 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006983 if (!Val.isInt()) {
6984 // FIXME: It would be better to produce the diagnostic for casting
6985 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00006986 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006987 return false;
6988 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006989 Result = Val.getInt();
6990 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006991}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006992
Richard Smithf57d8cb2011-12-09 22:58:01 +00006993/// Check whether the given declaration can be directly converted to an integral
6994/// rvalue. If not, no diagnostic is produced; there are other things we can
6995/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006996bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006997 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006998 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006999 // Check for signedness/width mismatches between E type and ECD value.
7000 bool SameSign = (ECD->getInitVal().isSigned()
7001 == E->getType()->isSignedIntegerOrEnumerationType());
7002 bool SameWidth = (ECD->getInitVal().getBitWidth()
7003 == Info.Ctx.getIntWidth(E->getType()));
7004 if (SameSign && SameWidth)
7005 return Success(ECD->getInitVal(), E);
7006 else {
7007 // Get rid of mismatch (otherwise Success assertions will fail)
7008 // by computing a new value matching the type of E.
7009 llvm::APSInt Val = ECD->getInitVal();
7010 if (!SameSign)
7011 Val.setIsSigned(!ECD->getInitVal().isSigned());
7012 if (!SameWidth)
7013 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7014 return Success(Val, E);
7015 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007016 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007017 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007018}
7019
Chris Lattner86ee2862008-10-06 06:40:35 +00007020/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7021/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007022static int EvaluateBuiltinClassifyType(const CallExpr *E,
7023 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007024 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007025 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007026 enum gcc_type_class {
7027 no_type_class = -1,
7028 void_type_class, integer_type_class, char_type_class,
7029 enumeral_type_class, boolean_type_class,
7030 pointer_type_class, reference_type_class, offset_type_class,
7031 real_type_class, complex_type_class,
7032 function_type_class, method_type_class,
7033 record_type_class, union_type_class,
7034 array_type_class, string_type_class,
7035 lang_type_class
7036 };
Mike Stump11289f42009-09-09 15:08:12 +00007037
7038 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007039 // ideal, however it is what gcc does.
7040 if (E->getNumArgs() == 0)
7041 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007042
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007043 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7044 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7045
7046 switch (CanTy->getTypeClass()) {
7047#define TYPE(ID, BASE)
7048#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7049#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7050#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7051#include "clang/AST/TypeNodes.def"
7052 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7053
7054 case Type::Builtin:
7055 switch (BT->getKind()) {
7056#define BUILTIN_TYPE(ID, SINGLETON_ID)
7057#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7058#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7059#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7060#include "clang/AST/BuiltinTypes.def"
7061 case BuiltinType::Void:
7062 return void_type_class;
7063
7064 case BuiltinType::Bool:
7065 return boolean_type_class;
7066
7067 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7068 case BuiltinType::UChar:
7069 case BuiltinType::UShort:
7070 case BuiltinType::UInt:
7071 case BuiltinType::ULong:
7072 case BuiltinType::ULongLong:
7073 case BuiltinType::UInt128:
7074 return integer_type_class;
7075
7076 case BuiltinType::NullPtr:
7077 return pointer_type_class;
7078
7079 case BuiltinType::WChar_U:
7080 case BuiltinType::Char16:
7081 case BuiltinType::Char32:
7082 case BuiltinType::ObjCId:
7083 case BuiltinType::ObjCClass:
7084 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007085#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7086 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007087#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007088 case BuiltinType::OCLSampler:
7089 case BuiltinType::OCLEvent:
7090 case BuiltinType::OCLClkEvent:
7091 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007092 case BuiltinType::OCLReserveID:
7093 case BuiltinType::Dependent:
7094 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7095 };
7096
7097 case Type::Enum:
7098 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7099 break;
7100
7101 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007102 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007103 break;
7104
7105 case Type::MemberPointer:
7106 if (CanTy->isMemberDataPointerType())
7107 return offset_type_class;
7108 else {
7109 // We expect member pointers to be either data or function pointers,
7110 // nothing else.
7111 assert(CanTy->isMemberFunctionPointerType());
7112 return method_type_class;
7113 }
7114
7115 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007116 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007117
7118 case Type::FunctionNoProto:
7119 case Type::FunctionProto:
7120 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7121
7122 case Type::Record:
7123 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7124 switch (RT->getDecl()->getTagKind()) {
7125 case TagTypeKind::TTK_Struct:
7126 case TagTypeKind::TTK_Class:
7127 case TagTypeKind::TTK_Interface:
7128 return record_type_class;
7129
7130 case TagTypeKind::TTK_Enum:
7131 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7132
7133 case TagTypeKind::TTK_Union:
7134 return union_type_class;
7135 }
7136 }
David Blaikie83d382b2011-09-23 05:06:16 +00007137 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007138
7139 case Type::ConstantArray:
7140 case Type::VariableArray:
7141 case Type::IncompleteArray:
7142 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7143
7144 case Type::BlockPointer:
7145 case Type::LValueReference:
7146 case Type::RValueReference:
7147 case Type::Vector:
7148 case Type::ExtVector:
7149 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007150 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007151 case Type::ObjCObject:
7152 case Type::ObjCInterface:
7153 case Type::ObjCObjectPointer:
7154 case Type::Pipe:
7155 case Type::Atomic:
7156 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7157 }
7158
7159 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007160}
7161
Richard Smith5fab0c92011-12-28 19:48:30 +00007162/// EvaluateBuiltinConstantPForLValue - Determine the result of
7163/// __builtin_constant_p when applied to the given lvalue.
7164///
7165/// An lvalue is only "constant" if it is a pointer or reference to the first
7166/// character of a string literal.
7167template<typename LValue>
7168static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007169 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007170 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7171}
7172
7173/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7174/// GCC as we can manage.
7175static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7176 QualType ArgType = Arg->getType();
7177
7178 // __builtin_constant_p always has one operand. The rules which gcc follows
7179 // are not precisely documented, but are as follows:
7180 //
7181 // - If the operand is of integral, floating, complex or enumeration type,
7182 // and can be folded to a known value of that type, it returns 1.
7183 // - If the operand and can be folded to a pointer to the first character
7184 // of a string literal (or such a pointer cast to an integral type), it
7185 // returns 1.
7186 //
7187 // Otherwise, it returns 0.
7188 //
7189 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7190 // its support for this does not currently work.
7191 if (ArgType->isIntegralOrEnumerationType()) {
7192 Expr::EvalResult Result;
7193 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7194 return false;
7195
7196 APValue &V = Result.Val;
7197 if (V.getKind() == APValue::Int)
7198 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007199 if (V.getKind() == APValue::LValue)
7200 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007201 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7202 return Arg->isEvaluatable(Ctx);
7203 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7204 LValue LV;
7205 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007206 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007207 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7208 : EvaluatePointer(Arg, LV, Info)) &&
7209 !Status.HasSideEffects)
7210 return EvaluateBuiltinConstantPForLValue(LV);
7211 }
7212
7213 // Anything else isn't considered to be sufficiently constant.
7214 return false;
7215}
7216
John McCall95007602010-05-10 23:27:23 +00007217/// Retrieves the "underlying object type" of the given expression,
7218/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007219static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007220 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7221 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007222 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007223 } else if (const Expr *E = B.get<const Expr*>()) {
7224 if (isa<CompoundLiteralExpr>(E))
7225 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007226 }
7227
7228 return QualType();
7229}
7230
George Burgess IV3a03fab2015-09-04 21:28:13 +00007231/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007232/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007233/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007234/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7235///
7236/// Always returns an RValue with a pointer representation.
7237static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7238 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7239
7240 auto *NoParens = E->IgnoreParens();
7241 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007242 if (Cast == nullptr)
7243 return NoParens;
7244
7245 // We only conservatively allow a few kinds of casts, because this code is
7246 // inherently a simple solution that seeks to support the common case.
7247 auto CastKind = Cast->getCastKind();
7248 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7249 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007250 return NoParens;
7251
7252 auto *SubExpr = Cast->getSubExpr();
7253 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7254 return NoParens;
7255 return ignorePointerCastsAndParens(SubExpr);
7256}
7257
George Burgess IVa51c4072015-10-16 01:49:01 +00007258/// Checks to see if the given LValue's Designator is at the end of the LValue's
7259/// record layout. e.g.
7260/// struct { struct { int a, b; } fst, snd; } obj;
7261/// obj.fst // no
7262/// obj.snd // yes
7263/// obj.fst.a // no
7264/// obj.fst.b // no
7265/// obj.snd.a // no
7266/// obj.snd.b // yes
7267///
7268/// Please note: this function is specialized for how __builtin_object_size
7269/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007270///
7271/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007272static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7273 assert(!LVal.Designator.Invalid);
7274
George Burgess IV4168d752016-06-27 19:40:41 +00007275 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7276 const RecordDecl *Parent = FD->getParent();
7277 Invalid = Parent->isInvalidDecl();
7278 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007279 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007280 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007281 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7282 };
7283
7284 auto &Base = LVal.getLValueBase();
7285 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7286 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007287 bool Invalid;
7288 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7289 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007290 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007291 for (auto *FD : IFD->chain()) {
7292 bool Invalid;
7293 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7294 return Invalid;
7295 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007296 }
7297 }
7298
George Burgess IVe3763372016-12-22 02:50:20 +00007299 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007300 QualType BaseType = getType(Base);
George Burgess IVe3763372016-12-22 02:50:20 +00007301 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7302 assert(isBaseAnAllocSizeCall(Base) &&
7303 "Unsized array in non-alloc_size call?");
7304 // If this is an alloc_size base, we should ignore the initial array index
7305 ++I;
7306 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7307 }
7308
7309 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7310 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007311 if (BaseType->isArrayType()) {
7312 // Because __builtin_object_size treats arrays as objects, we can ignore
7313 // the index iff this is the last array in the Designator.
7314 if (I + 1 == E)
7315 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007316 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7317 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007318 if (Index + 1 != CAT->getSize())
7319 return false;
7320 BaseType = CAT->getElementType();
7321 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007322 const auto *CT = BaseType->castAs<ComplexType>();
7323 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007324 if (Index != 1)
7325 return false;
7326 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007327 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007328 bool Invalid;
7329 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7330 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007331 BaseType = FD->getType();
7332 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007333 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007334 return false;
7335 }
7336 }
7337 return true;
7338}
7339
George Burgess IVe3763372016-12-22 02:50:20 +00007340/// Tests to see if the LValue has a user-specified designator (that isn't
7341/// necessarily valid). Note that this always returns 'true' if the LValue has
7342/// an unsized array as its first designator entry, because there's currently no
7343/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007344static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007345 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007346 return false;
7347
George Burgess IVe3763372016-12-22 02:50:20 +00007348 if (!LVal.Designator.Entries.empty())
7349 return LVal.Designator.isMostDerivedAnUnsizedArray();
7350
George Burgess IVa51c4072015-10-16 01:49:01 +00007351 if (!LVal.InvalidBase)
7352 return true;
7353
George Burgess IVe3763372016-12-22 02:50:20 +00007354 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7355 // the LValueBase.
7356 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7357 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007358}
7359
George Burgess IVe3763372016-12-22 02:50:20 +00007360/// Attempts to detect a user writing into a piece of memory that's impossible
7361/// to figure out the size of by just using types.
7362static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7363 const SubobjectDesignator &Designator = LVal.Designator;
7364 // Notes:
7365 // - Users can only write off of the end when we have an invalid base. Invalid
7366 // bases imply we don't know where the memory came from.
7367 // - We used to be a bit more aggressive here; we'd only be conservative if
7368 // the array at the end was flexible, or if it had 0 or 1 elements. This
7369 // broke some common standard library extensions (PR30346), but was
7370 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7371 // with some sort of whitelist. OTOH, it seems that GCC is always
7372 // conservative with the last element in structs (if it's an array), so our
7373 // current behavior is more compatible than a whitelisting approach would
7374 // be.
7375 return LVal.InvalidBase &&
7376 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7377 Designator.MostDerivedIsArrayElement &&
7378 isDesignatorAtObjectEnd(Ctx, LVal);
7379}
7380
7381/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7382/// Fails if the conversion would cause loss of precision.
7383static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7384 CharUnits &Result) {
7385 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7386 if (Int.ugt(CharUnitsMax))
7387 return false;
7388 Result = CharUnits::fromQuantity(Int.getZExtValue());
7389 return true;
7390}
7391
7392/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7393/// determine how many bytes exist from the beginning of the object to either
7394/// the end of the current subobject, or the end of the object itself, depending
7395/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007396///
George Burgess IVe3763372016-12-22 02:50:20 +00007397/// If this returns false, the value of Result is undefined.
7398static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7399 unsigned Type, const LValue &LVal,
7400 CharUnits &EndOffset) {
7401 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007402
George Burgess IV7fb7e362017-01-03 23:35:19 +00007403 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7404 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7405 return false;
7406 return HandleSizeof(Info, ExprLoc, Ty, Result);
7407 };
7408
George Burgess IVe3763372016-12-22 02:50:20 +00007409 // We want to evaluate the size of the entire object. This is a valid fallback
7410 // for when Type=1 and the designator is invalid, because we're asked for an
7411 // upper-bound.
7412 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7413 // Type=3 wants a lower bound, so we can't fall back to this.
7414 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007415 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007416
7417 llvm::APInt APEndOffset;
7418 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7419 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7420 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7421
7422 if (LVal.InvalidBase)
7423 return false;
7424
7425 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007426 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007427 }
7428
George Burgess IVe3763372016-12-22 02:50:20 +00007429 // We want to evaluate the size of a subobject.
7430 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007431
7432 // The following is a moderately common idiom in C:
7433 //
7434 // struct Foo { int a; char c[1]; };
7435 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7436 // strcpy(&F->c[0], Bar);
7437 //
George Burgess IVe3763372016-12-22 02:50:20 +00007438 // In order to not break too much legacy code, we need to support it.
7439 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7440 // If we can resolve this to an alloc_size call, we can hand that back,
7441 // because we know for certain how many bytes there are to write to.
7442 llvm::APInt APEndOffset;
7443 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7444 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7445 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7446
7447 // If we cannot determine the size of the initial allocation, then we can't
7448 // given an accurate upper-bound. However, we are still able to give
7449 // conservative lower-bounds for Type=3.
7450 if (Type == 1)
7451 return false;
7452 }
7453
7454 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007455 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007456 return false;
7457
George Burgess IVe3763372016-12-22 02:50:20 +00007458 // According to the GCC documentation, we want the size of the subobject
7459 // denoted by the pointer. But that's not quite right -- what we actually
7460 // want is the size of the immediately-enclosing array, if there is one.
7461 int64_t ElemsRemaining;
7462 if (Designator.MostDerivedIsArrayElement &&
7463 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7464 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7465 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7466 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7467 } else {
7468 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7469 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007470
George Burgess IVe3763372016-12-22 02:50:20 +00007471 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7472 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007473}
7474
George Burgess IVe3763372016-12-22 02:50:20 +00007475/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7476/// returns true and stores the result in @p Size.
7477///
7478/// If @p WasError is non-null, this will report whether the failure to evaluate
7479/// is to be treated as an Error in IntExprEvaluator.
7480static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7481 EvalInfo &Info, uint64_t &Size) {
7482 // Determine the denoted object.
7483 LValue LVal;
7484 {
7485 // The operand of __builtin_object_size is never evaluated for side-effects.
7486 // If there are any, but we can determine the pointed-to object anyway, then
7487 // ignore the side-effects.
7488 SpeculativeEvaluationRAII SpeculativeEval(Info);
7489 FoldOffsetRAII Fold(Info);
7490
7491 if (E->isGLValue()) {
7492 // It's possible for us to be given GLValues if we're called via
7493 // Expr::tryEvaluateObjectSize.
7494 APValue RVal;
7495 if (!EvaluateAsRValue(Info, E, RVal))
7496 return false;
7497 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007498 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7499 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007500 return false;
7501 }
7502
7503 // If we point to before the start of the object, there are no accessible
7504 // bytes.
7505 if (LVal.getLValueOffset().isNegative()) {
7506 Size = 0;
7507 return true;
7508 }
7509
7510 CharUnits EndOffset;
7511 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7512 return false;
7513
7514 // If we've fallen outside of the end offset, just pretend there's nothing to
7515 // write to/read from.
7516 if (EndOffset <= LVal.getLValueOffset())
7517 Size = 0;
7518 else
7519 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7520 return true;
John McCall95007602010-05-10 23:27:23 +00007521}
7522
Peter Collingbournee9200682011-05-13 03:29:01 +00007523bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007524 if (unsigned BuiltinOp = E->getBuiltinCallee())
7525 return VisitBuiltinCallExpr(E, BuiltinOp);
7526
7527 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7528}
7529
7530bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7531 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007532 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007533 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007534 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007535
7536 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007537 // The type was checked when we built the expression.
7538 unsigned Type =
7539 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7540 assert(Type <= 3 && "unexpected type");
7541
George Burgess IVe3763372016-12-22 02:50:20 +00007542 uint64_t Size;
7543 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7544 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007545
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007546 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007547 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007548
Richard Smith01ade172012-05-23 04:13:20 +00007549 // Expression had no side effects, but we couldn't statically determine the
7550 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007551 switch (Info.EvalMode) {
7552 case EvalInfo::EM_ConstantExpression:
7553 case EvalInfo::EM_PotentialConstantExpression:
7554 case EvalInfo::EM_ConstantFold:
7555 case EvalInfo::EM_EvaluateForOverflow:
7556 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007557 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007558 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007559 return Error(E);
7560 case EvalInfo::EM_ConstantExpressionUnevaluated:
7561 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007562 // Reduce it to a constant now.
7563 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007564 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007565
7566 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007567 }
7568
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007569 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007570 case Builtin::BI__builtin_bswap32:
7571 case Builtin::BI__builtin_bswap64: {
7572 APSInt Val;
7573 if (!EvaluateInteger(E->getArg(0), Val, Info))
7574 return false;
7575
7576 return Success(Val.byteSwap(), E);
7577 }
7578
Richard Smith8889a3d2013-06-13 06:26:32 +00007579 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007580 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007581
7582 // FIXME: BI__builtin_clrsb
7583 // FIXME: BI__builtin_clrsbl
7584 // FIXME: BI__builtin_clrsbll
7585
Richard Smith80b3c8e2013-06-13 05:04:16 +00007586 case Builtin::BI__builtin_clz:
7587 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007588 case Builtin::BI__builtin_clzll:
7589 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007590 APSInt Val;
7591 if (!EvaluateInteger(E->getArg(0), Val, Info))
7592 return false;
7593 if (!Val)
7594 return Error(E);
7595
7596 return Success(Val.countLeadingZeros(), E);
7597 }
7598
Richard Smith8889a3d2013-06-13 06:26:32 +00007599 case Builtin::BI__builtin_constant_p:
7600 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7601
Richard Smith80b3c8e2013-06-13 05:04:16 +00007602 case Builtin::BI__builtin_ctz:
7603 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007604 case Builtin::BI__builtin_ctzll:
7605 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007606 APSInt Val;
7607 if (!EvaluateInteger(E->getArg(0), Val, Info))
7608 return false;
7609 if (!Val)
7610 return Error(E);
7611
7612 return Success(Val.countTrailingZeros(), E);
7613 }
7614
Richard Smith8889a3d2013-06-13 06:26:32 +00007615 case Builtin::BI__builtin_eh_return_data_regno: {
7616 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7617 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7618 return Success(Operand, E);
7619 }
7620
7621 case Builtin::BI__builtin_expect:
7622 return Visit(E->getArg(0));
7623
7624 case Builtin::BI__builtin_ffs:
7625 case Builtin::BI__builtin_ffsl:
7626 case Builtin::BI__builtin_ffsll: {
7627 APSInt Val;
7628 if (!EvaluateInteger(E->getArg(0), Val, Info))
7629 return false;
7630
7631 unsigned N = Val.countTrailingZeros();
7632 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7633 }
7634
7635 case Builtin::BI__builtin_fpclassify: {
7636 APFloat Val(0.0);
7637 if (!EvaluateFloat(E->getArg(5), Val, Info))
7638 return false;
7639 unsigned Arg;
7640 switch (Val.getCategory()) {
7641 case APFloat::fcNaN: Arg = 0; break;
7642 case APFloat::fcInfinity: Arg = 1; break;
7643 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7644 case APFloat::fcZero: Arg = 4; break;
7645 }
7646 return Visit(E->getArg(Arg));
7647 }
7648
7649 case Builtin::BI__builtin_isinf_sign: {
7650 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007651 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007652 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7653 }
7654
Richard Smithea3019d2013-10-15 19:07:14 +00007655 case Builtin::BI__builtin_isinf: {
7656 APFloat Val(0.0);
7657 return EvaluateFloat(E->getArg(0), Val, Info) &&
7658 Success(Val.isInfinity() ? 1 : 0, E);
7659 }
7660
7661 case Builtin::BI__builtin_isfinite: {
7662 APFloat Val(0.0);
7663 return EvaluateFloat(E->getArg(0), Val, Info) &&
7664 Success(Val.isFinite() ? 1 : 0, E);
7665 }
7666
7667 case Builtin::BI__builtin_isnan: {
7668 APFloat Val(0.0);
7669 return EvaluateFloat(E->getArg(0), Val, Info) &&
7670 Success(Val.isNaN() ? 1 : 0, E);
7671 }
7672
7673 case Builtin::BI__builtin_isnormal: {
7674 APFloat Val(0.0);
7675 return EvaluateFloat(E->getArg(0), Val, Info) &&
7676 Success(Val.isNormal() ? 1 : 0, E);
7677 }
7678
Richard Smith8889a3d2013-06-13 06:26:32 +00007679 case Builtin::BI__builtin_parity:
7680 case Builtin::BI__builtin_parityl:
7681 case Builtin::BI__builtin_parityll: {
7682 APSInt Val;
7683 if (!EvaluateInteger(E->getArg(0), Val, Info))
7684 return false;
7685
7686 return Success(Val.countPopulation() % 2, E);
7687 }
7688
Richard Smith80b3c8e2013-06-13 05:04:16 +00007689 case Builtin::BI__builtin_popcount:
7690 case Builtin::BI__builtin_popcountl:
7691 case Builtin::BI__builtin_popcountll: {
7692 APSInt Val;
7693 if (!EvaluateInteger(E->getArg(0), Val, Info))
7694 return false;
7695
7696 return Success(Val.countPopulation(), E);
7697 }
7698
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007699 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007700 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007701 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007702 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007703 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007704 << /*isConstexpr*/0 << /*isConstructor*/0
7705 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007706 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007707 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007708 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007709 case Builtin::BI__builtin_strlen:
7710 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007711 // As an extension, we support __builtin_strlen() as a constant expression,
7712 // and support folding strlen() to a constant.
7713 LValue String;
7714 if (!EvaluatePointer(E->getArg(0), String, Info))
7715 return false;
7716
Richard Smith8110c9d2016-11-29 19:45:17 +00007717 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7718
Richard Smithe6c19f22013-11-15 02:10:04 +00007719 // Fast path: if it's a string literal, search the string value.
7720 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7721 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007722 // The string literal may have embedded null characters. Find the first
7723 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007724 StringRef Str = S->getBytes();
7725 int64_t Off = String.Offset.getQuantity();
7726 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007727 S->getCharByteWidth() == 1 &&
7728 // FIXME: Add fast-path for wchar_t too.
7729 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007730 Str = Str.substr(Off);
7731
7732 StringRef::size_type Pos = Str.find(0);
7733 if (Pos != StringRef::npos)
7734 Str = Str.substr(0, Pos);
7735
7736 return Success(Str.size(), E);
7737 }
7738
7739 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007740 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007741
7742 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007743 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7744 APValue Char;
7745 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7746 !Char.isInt())
7747 return false;
7748 if (!Char.getInt())
7749 return Success(Strlen, E);
7750 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7751 return false;
7752 }
7753 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007754
Richard Smithe151bab2016-11-11 23:43:35 +00007755 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007756 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007757 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007758 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007759 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007760 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007761 // A call to strlen is not a constant expression.
7762 if (Info.getLangOpts().CPlusPlus11)
7763 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7764 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007765 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007766 else
7767 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7768 // Fall through.
7769 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007770 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007771 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007772 case Builtin::BI__builtin_wcsncmp:
7773 case Builtin::BI__builtin_memcmp:
7774 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007775 LValue String1, String2;
7776 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7777 !EvaluatePointer(E->getArg(1), String2, Info))
7778 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007779
7780 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7781
Richard Smithe151bab2016-11-11 23:43:35 +00007782 uint64_t MaxLength = uint64_t(-1);
7783 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007784 BuiltinOp != Builtin::BIwcscmp &&
7785 BuiltinOp != Builtin::BI__builtin_strcmp &&
7786 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007787 APSInt N;
7788 if (!EvaluateInteger(E->getArg(2), N, Info))
7789 return false;
7790 MaxLength = N.getExtValue();
7791 }
7792 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007793 BuiltinOp != Builtin::BIwmemcmp &&
7794 BuiltinOp != Builtin::BI__builtin_memcmp &&
7795 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007796 for (; MaxLength; --MaxLength) {
7797 APValue Char1, Char2;
7798 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7799 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7800 !Char1.isInt() || !Char2.isInt())
7801 return false;
7802 if (Char1.getInt() != Char2.getInt())
7803 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7804 if (StopAtNull && !Char1.getInt())
7805 return Success(0, E);
7806 assert(!(StopAtNull && !Char2.getInt()));
7807 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7808 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7809 return false;
7810 }
7811 // We hit the strncmp / memcmp limit.
7812 return Success(0, E);
7813 }
7814
Richard Smith01ba47d2012-04-13 00:45:38 +00007815 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007816 case Builtin::BI__atomic_is_lock_free:
7817 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007818 APSInt SizeVal;
7819 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7820 return false;
7821
7822 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7823 // of two less than the maximum inline atomic width, we know it is
7824 // lock-free. If the size isn't a power of two, or greater than the
7825 // maximum alignment where we promote atomics, we know it is not lock-free
7826 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7827 // the answer can only be determined at runtime; for example, 16-byte
7828 // atomics have lock-free implementations on some, but not all,
7829 // x86-64 processors.
7830
7831 // Check power-of-two.
7832 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007833 if (Size.isPowerOfTwo()) {
7834 // Check against inlining width.
7835 unsigned InlineWidthBits =
7836 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7837 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7838 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7839 Size == CharUnits::One() ||
7840 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7841 Expr::NPC_NeverValueDependent))
7842 // OK, we will inline appropriately-aligned operations of this size,
7843 // and _Atomic(T) is appropriately-aligned.
7844 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007845
Richard Smith01ba47d2012-04-13 00:45:38 +00007846 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7847 castAs<PointerType>()->getPointeeType();
7848 if (!PointeeType->isIncompleteType() &&
7849 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7850 // OK, we will inline operations on this object.
7851 return Success(1, E);
7852 }
7853 }
7854 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007855
Richard Smith01ba47d2012-04-13 00:45:38 +00007856 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7857 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007858 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007859 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007860}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007861
Richard Smith8b3497e2011-10-31 01:37:14 +00007862static bool HasSameBase(const LValue &A, const LValue &B) {
7863 if (!A.getLValueBase())
7864 return !B.getLValueBase();
7865 if (!B.getLValueBase())
7866 return false;
7867
Richard Smithce40ad62011-11-12 22:28:03 +00007868 if (A.getLValueBase().getOpaqueValue() !=
7869 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007870 const Decl *ADecl = GetLValueBaseDecl(A);
7871 if (!ADecl)
7872 return false;
7873 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007874 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007875 return false;
7876 }
7877
7878 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007879 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007880}
7881
Richard Smithd20f1e62014-10-21 23:01:04 +00007882/// \brief Determine whether this is a pointer past the end of the complete
7883/// object referred to by the lvalue.
7884static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7885 const LValue &LV) {
7886 // A null pointer can be viewed as being "past the end" but we don't
7887 // choose to look at it that way here.
7888 if (!LV.getLValueBase())
7889 return false;
7890
7891 // If the designator is valid and refers to a subobject, we're not pointing
7892 // past the end.
7893 if (!LV.getLValueDesignator().Invalid &&
7894 !LV.getLValueDesignator().isOnePastTheEnd())
7895 return false;
7896
David Majnemerc378ca52015-08-29 08:32:55 +00007897 // A pointer to an incomplete type might be past-the-end if the type's size is
7898 // zero. We cannot tell because the type is incomplete.
7899 QualType Ty = getType(LV.getLValueBase());
7900 if (Ty->isIncompleteType())
7901 return true;
7902
Richard Smithd20f1e62014-10-21 23:01:04 +00007903 // We're a past-the-end pointer if we point to the byte after the object,
7904 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007905 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007906 return LV.getLValueOffset() == Size;
7907}
7908
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007909namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007910
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007911/// \brief Data recursive integer evaluator of certain binary operators.
7912///
7913/// We use a data recursive algorithm for binary operators so that we are able
7914/// to handle extreme cases of chained binary operators without causing stack
7915/// overflow.
7916class DataRecursiveIntBinOpEvaluator {
7917 struct EvalResult {
7918 APValue Val;
7919 bool Failed;
7920
7921 EvalResult() : Failed(false) { }
7922
7923 void swap(EvalResult &RHS) {
7924 Val.swap(RHS.Val);
7925 Failed = RHS.Failed;
7926 RHS.Failed = false;
7927 }
7928 };
7929
7930 struct Job {
7931 const Expr *E;
7932 EvalResult LHSResult; // meaningful only for binary operator expression.
7933 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007934
David Blaikie73726062015-08-12 23:09:24 +00007935 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007936 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007937
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007938 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007939 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007940 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007941
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007942 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007943 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007944 };
7945
7946 SmallVector<Job, 16> Queue;
7947
7948 IntExprEvaluator &IntEval;
7949 EvalInfo &Info;
7950 APValue &FinalResult;
7951
7952public:
7953 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7954 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7955
7956 /// \brief True if \param E is a binary operator that we are going to handle
7957 /// data recursively.
7958 /// We handle binary operators that are comma, logical, or that have operands
7959 /// with integral or enumeration type.
7960 static bool shouldEnqueue(const BinaryOperator *E) {
7961 return E->getOpcode() == BO_Comma ||
7962 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007963 (E->isRValue() &&
7964 E->getType()->isIntegralOrEnumerationType() &&
7965 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007966 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007967 }
7968
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007969 bool Traverse(const BinaryOperator *E) {
7970 enqueue(E);
7971 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007972 while (!Queue.empty())
7973 process(PrevResult);
7974
7975 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007976
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007977 FinalResult.swap(PrevResult.Val);
7978 return true;
7979 }
7980
7981private:
7982 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7983 return IntEval.Success(Value, E, Result);
7984 }
7985 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7986 return IntEval.Success(Value, E, Result);
7987 }
7988 bool Error(const Expr *E) {
7989 return IntEval.Error(E);
7990 }
7991 bool Error(const Expr *E, diag::kind D) {
7992 return IntEval.Error(E, D);
7993 }
7994
7995 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7996 return Info.CCEDiag(E, D);
7997 }
7998
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007999 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8000 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008001 bool &SuppressRHSDiags);
8002
8003 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8004 const BinaryOperator *E, APValue &Result);
8005
8006 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8007 Result.Failed = !Evaluate(Result.Val, Info, E);
8008 if (Result.Failed)
8009 Result.Val = APValue();
8010 }
8011
Richard Trieuba4d0872012-03-21 23:30:30 +00008012 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008013
8014 void enqueue(const Expr *E) {
8015 E = E->IgnoreParens();
8016 Queue.resize(Queue.size()+1);
8017 Queue.back().E = E;
8018 Queue.back().Kind = Job::AnyExprKind;
8019 }
8020};
8021
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008022}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008023
8024bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008025 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008026 bool &SuppressRHSDiags) {
8027 if (E->getOpcode() == BO_Comma) {
8028 // Ignore LHS but note if we could not evaluate it.
8029 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008030 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008031 return true;
8032 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008033
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008034 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008035 bool LHSAsBool;
8036 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008037 // We were able to evaluate the LHS, see if we can get away with not
8038 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008039 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8040 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008041 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008042 }
8043 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008044 LHSResult.Failed = true;
8045
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008046 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008047 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008048 if (!Info.noteSideEffect())
8049 return false;
8050
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008051 // We can't evaluate the LHS; however, sometimes the result
8052 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8053 // Don't ignore RHS and suppress diagnostics from this arm.
8054 SuppressRHSDiags = true;
8055 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008056
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008057 return true;
8058 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008059
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008060 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8061 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008062
George Burgess IVa145e252016-05-25 22:38:36 +00008063 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008064 return false; // Ignore RHS;
8065
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008066 return true;
8067}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008068
Richard Smithd6cc1982017-01-31 02:23:02 +00008069static void addOrSubLValueAsInteger(APValue &LVal, APSInt Index, bool IsSub) {
8070 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8071 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8072 // offsets.
8073 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8074 CharUnits &Offset = LVal.getLValueOffset();
8075 uint64_t Offset64 = Offset.getQuantity();
8076 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8077 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8078 : Offset64 + Index64);
8079}
8080
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008081bool DataRecursiveIntBinOpEvaluator::
8082 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8083 const BinaryOperator *E, APValue &Result) {
8084 if (E->getOpcode() == BO_Comma) {
8085 if (RHSResult.Failed)
8086 return false;
8087 Result = RHSResult.Val;
8088 return true;
8089 }
8090
8091 if (E->isLogicalOp()) {
8092 bool lhsResult, rhsResult;
8093 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8094 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
8095
8096 if (LHSIsOK) {
8097 if (RHSIsOK) {
8098 if (E->getOpcode() == BO_LOr)
8099 return Success(lhsResult || rhsResult, E, Result);
8100 else
8101 return Success(lhsResult && rhsResult, E, Result);
8102 }
8103 } else {
8104 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008105 // We can't evaluate the LHS; however, sometimes the result
8106 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8107 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008108 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008109 }
8110 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008111
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008112 return false;
8113 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008114
8115 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8116 E->getRHS()->getType()->isIntegralOrEnumerationType());
8117
8118 if (LHSResult.Failed || RHSResult.Failed)
8119 return false;
8120
8121 const APValue &LHSVal = LHSResult.Val;
8122 const APValue &RHSVal = RHSResult.Val;
8123
8124 // Handle cases like (unsigned long)&a + 4.
8125 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8126 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008127 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008128 return true;
8129 }
8130
8131 // Handle cases like 4 + (unsigned long)&a
8132 if (E->getOpcode() == BO_Add &&
8133 RHSVal.isLValue() && LHSVal.isInt()) {
8134 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008135 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008136 return true;
8137 }
8138
8139 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8140 // Handle (intptr_t)&&A - (intptr_t)&&B.
8141 if (!LHSVal.getLValueOffset().isZero() ||
8142 !RHSVal.getLValueOffset().isZero())
8143 return false;
8144 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8145 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8146 if (!LHSExpr || !RHSExpr)
8147 return false;
8148 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8149 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8150 if (!LHSAddrExpr || !RHSAddrExpr)
8151 return false;
8152 // Make sure both labels come from the same function.
8153 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8154 RHSAddrExpr->getLabel()->getDeclContext())
8155 return false;
8156 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8157 return true;
8158 }
Richard Smith43e77732013-05-07 04:50:00 +00008159
8160 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008161 if (!LHSVal.isInt() || !RHSVal.isInt())
8162 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008163
8164 // Set up the width and signedness manually, in case it can't be deduced
8165 // from the operation we're performing.
8166 // FIXME: Don't do this in the cases where we can deduce it.
8167 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8168 E->getType()->isUnsignedIntegerOrEnumerationType());
8169 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8170 RHSVal.getInt(), Value))
8171 return false;
8172 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008173}
8174
Richard Trieuba4d0872012-03-21 23:30:30 +00008175void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008176 Job &job = Queue.back();
8177
8178 switch (job.Kind) {
8179 case Job::AnyExprKind: {
8180 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8181 if (shouldEnqueue(Bop)) {
8182 job.Kind = Job::BinOpKind;
8183 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008184 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008185 }
8186 }
8187
8188 EvaluateExpr(job.E, Result);
8189 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008190 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008191 }
8192
8193 case Job::BinOpKind: {
8194 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008195 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008196 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008197 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008198 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008199 }
8200 if (SuppressRHSDiags)
8201 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008202 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008203 job.Kind = Job::BinOpVisitedLHSKind;
8204 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008205 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008206 }
8207
8208 case Job::BinOpVisitedLHSKind: {
8209 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8210 EvalResult RHS;
8211 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008212 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008213 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008214 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008215 }
8216 }
8217
8218 llvm_unreachable("Invalid Job::Kind!");
8219}
8220
George Burgess IV8c892b52016-05-25 22:31:54 +00008221namespace {
8222/// Used when we determine that we should fail, but can keep evaluating prior to
8223/// noting that we had a failure.
8224class DelayedNoteFailureRAII {
8225 EvalInfo &Info;
8226 bool NoteFailure;
8227
8228public:
8229 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8230 : Info(Info), NoteFailure(NoteFailure) {}
8231 ~DelayedNoteFailureRAII() {
8232 if (NoteFailure) {
8233 bool ContinueAfterFailure = Info.noteFailure();
8234 (void)ContinueAfterFailure;
8235 assert(ContinueAfterFailure &&
8236 "Shouldn't have kept evaluating on failure.");
8237 }
8238 }
8239};
8240}
8241
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008242bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008243 // We don't call noteFailure immediately because the assignment happens after
8244 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008245 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008246 return Error(E);
8247
George Burgess IV8c892b52016-05-25 22:31:54 +00008248 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008249 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8250 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008251
Anders Carlssonacc79812008-11-16 07:17:21 +00008252 QualType LHSTy = E->getLHS()->getType();
8253 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008254
Chandler Carruthb29a7432014-10-11 11:03:30 +00008255 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008256 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008257 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008258 if (E->isAssignmentOp()) {
8259 LValue LV;
8260 EvaluateLValue(E->getLHS(), LV, Info);
8261 LHSOK = false;
8262 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008263 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8264 if (LHSOK) {
8265 LHS.makeComplexFloat();
8266 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8267 }
8268 } else {
8269 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8270 }
George Burgess IVa145e252016-05-25 22:38:36 +00008271 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008272 return false;
8273
Chandler Carruthb29a7432014-10-11 11:03:30 +00008274 if (E->getRHS()->getType()->isRealFloatingType()) {
8275 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8276 return false;
8277 RHS.makeComplexFloat();
8278 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8279 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008280 return false;
8281
8282 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008283 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008284 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008285 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008286 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8287
John McCalle3027922010-08-25 11:45:40 +00008288 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008289 return Success((CR_r == APFloat::cmpEqual &&
8290 CR_i == APFloat::cmpEqual), E);
8291 else {
John McCalle3027922010-08-25 11:45:40 +00008292 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008293 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008294 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008295 CR_r == APFloat::cmpLessThan ||
8296 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008297 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008298 CR_i == APFloat::cmpLessThan ||
8299 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008300 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008301 } else {
John McCalle3027922010-08-25 11:45:40 +00008302 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008303 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8304 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8305 else {
John McCalle3027922010-08-25 11:45:40 +00008306 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008307 "Invalid compex comparison.");
8308 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8309 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8310 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008311 }
8312 }
Mike Stump11289f42009-09-09 15:08:12 +00008313
Anders Carlssonacc79812008-11-16 07:17:21 +00008314 if (LHSTy->isRealFloatingType() &&
8315 RHSTy->isRealFloatingType()) {
8316 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008317
Richard Smith253c2a32012-01-27 01:14:48 +00008318 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008319 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008320 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008321
Richard Smith253c2a32012-01-27 01:14:48 +00008322 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008323 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008324
Anders Carlssonacc79812008-11-16 07:17:21 +00008325 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008326
Anders Carlssonacc79812008-11-16 07:17:21 +00008327 switch (E->getOpcode()) {
8328 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008329 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008330 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008331 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008332 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008333 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008334 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008335 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008336 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008337 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008338 E);
John McCalle3027922010-08-25 11:45:40 +00008339 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008340 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008341 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008342 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008343 || CR == APFloat::cmpLessThan
8344 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008345 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008346 }
Mike Stump11289f42009-09-09 15:08:12 +00008347
Eli Friedmana38da572009-04-28 19:17:36 +00008348 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008349 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008350 LValue LHSValue, RHSValue;
8351
8352 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008353 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008354 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008355
Richard Smith253c2a32012-01-27 01:14:48 +00008356 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008357 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008358
Richard Smith8b3497e2011-10-31 01:37:14 +00008359 // Reject differing bases from the normal codepath; we special-case
8360 // comparisons to null.
8361 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008362 if (E->getOpcode() == BO_Sub) {
8363 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008364 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008365 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008366 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008367 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008368 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008369 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008370 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8371 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8372 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008373 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008374 // Make sure both labels come from the same function.
8375 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8376 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008377 return Error(E);
8378 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008379 }
Richard Smith83c68212011-10-31 05:11:32 +00008380 // Inequalities and subtractions between unrelated pointers have
8381 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008382 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008383 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008384 // A constant address may compare equal to the address of a symbol.
8385 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008386 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008387 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8388 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008389 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008390 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008391 // distinct addresses. In clang, the result of such a comparison is
8392 // unspecified, so it is not a constant expression. However, we do know
8393 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008394 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8395 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008396 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008397 // We can't tell whether weak symbols will end up pointing to the same
8398 // object.
8399 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008400 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008401 // We can't compare the address of the start of one object with the
8402 // past-the-end address of another object, per C++ DR1652.
8403 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8404 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8405 (RHSValue.Base && RHSValue.Offset.isZero() &&
8406 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8407 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008408 // We can't tell whether an object is at the same address as another
8409 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008410 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8411 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008412 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008413 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008414 // (Note that clang defaults to -fmerge-all-constants, which can
8415 // lead to inconsistent results for comparisons involving the address
8416 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008417 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008418 }
Eli Friedman64004332009-03-23 04:38:34 +00008419
Richard Smith1b470412012-02-01 08:10:20 +00008420 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8421 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8422
Richard Smith84f6dcf2012-02-02 01:16:57 +00008423 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8424 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8425
John McCalle3027922010-08-25 11:45:40 +00008426 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008427 // C++11 [expr.add]p6:
8428 // Unless both pointers point to elements of the same array object, or
8429 // one past the last element of the array object, the behavior is
8430 // undefined.
8431 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8432 !AreElementsOfSameArray(getType(LHSValue.Base),
8433 LHSDesignator, RHSDesignator))
8434 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8435
Chris Lattner882bdf22010-04-20 17:13:14 +00008436 QualType Type = E->getLHS()->getType();
8437 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008438
Richard Smithd62306a2011-11-10 06:34:14 +00008439 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008440 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008441 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008442
Richard Smith84c6b3d2013-09-10 21:34:14 +00008443 // As an extension, a type may have zero size (empty struct or union in
8444 // C, array of zero length). Pointer subtraction in such cases has
8445 // undefined behavior, so is not constant.
8446 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008447 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008448 << ElementType;
8449 return false;
8450 }
8451
Richard Smith1b470412012-02-01 08:10:20 +00008452 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8453 // and produce incorrect results when it overflows. Such behavior
8454 // appears to be non-conforming, but is common, so perhaps we should
8455 // assume the standard intended for such cases to be undefined behavior
8456 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008457
Richard Smith1b470412012-02-01 08:10:20 +00008458 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8459 // overflow in the final conversion to ptrdiff_t.
8460 APSInt LHS(
8461 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8462 APSInt RHS(
8463 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8464 APSInt ElemSize(
8465 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8466 APSInt TrueResult = (LHS - RHS) / ElemSize;
8467 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8468
Richard Smith0c6124b2015-12-03 01:36:22 +00008469 if (Result.extend(65) != TrueResult &&
8470 !HandleOverflow(Info, E, TrueResult, E->getType()))
8471 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008472 return Success(Result, E);
8473 }
Richard Smithde21b242012-01-31 06:41:30 +00008474
8475 // C++11 [expr.rel]p3:
8476 // Pointers to void (after pointer conversions) can be compared, with a
8477 // result defined as follows: If both pointers represent the same
8478 // address or are both the null pointer value, the result is true if the
8479 // operator is <= or >= and false otherwise; otherwise the result is
8480 // unspecified.
8481 // We interpret this as applying to pointers to *cv* void.
8482 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008483 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008484 CCEDiag(E, diag::note_constexpr_void_comparison);
8485
Richard Smith84f6dcf2012-02-02 01:16:57 +00008486 // C++11 [expr.rel]p2:
8487 // - If two pointers point to non-static data members of the same object,
8488 // or to subobjects or array elements fo such members, recursively, the
8489 // pointer to the later declared member compares greater provided the
8490 // two members have the same access control and provided their class is
8491 // not a union.
8492 // [...]
8493 // - Otherwise pointer comparisons are unspecified.
8494 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8495 E->isRelationalOp()) {
8496 bool WasArrayIndex;
8497 unsigned Mismatch =
8498 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8499 RHSDesignator, WasArrayIndex);
8500 // At the point where the designators diverge, the comparison has a
8501 // specified value if:
8502 // - we are comparing array indices
8503 // - we are comparing fields of a union, or fields with the same access
8504 // Otherwise, the result is unspecified and thus the comparison is not a
8505 // constant expression.
8506 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8507 Mismatch < RHSDesignator.Entries.size()) {
8508 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8509 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8510 if (!LF && !RF)
8511 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8512 else if (!LF)
8513 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8514 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8515 << RF->getParent() << RF;
8516 else if (!RF)
8517 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8518 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8519 << LF->getParent() << LF;
8520 else if (!LF->getParent()->isUnion() &&
8521 LF->getAccess() != RF->getAccess())
8522 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8523 << LF << LF->getAccess() << RF << RF->getAccess()
8524 << LF->getParent();
8525 }
8526 }
8527
Eli Friedman6c31cb42012-04-16 04:30:08 +00008528 // The comparison here must be unsigned, and performed with the same
8529 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008530 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8531 uint64_t CompareLHS = LHSOffset.getQuantity();
8532 uint64_t CompareRHS = RHSOffset.getQuantity();
8533 assert(PtrSize <= 64 && "Unexpected pointer width");
8534 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8535 CompareLHS &= Mask;
8536 CompareRHS &= Mask;
8537
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008538 // If there is a base and this is a relational operator, we can only
8539 // compare pointers within the object in question; otherwise, the result
8540 // depends on where the object is located in memory.
8541 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8542 QualType BaseTy = getType(LHSValue.Base);
8543 if (BaseTy->isIncompleteType())
8544 return Error(E);
8545 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8546 uint64_t OffsetLimit = Size.getQuantity();
8547 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8548 return Error(E);
8549 }
8550
Richard Smith8b3497e2011-10-31 01:37:14 +00008551 switch (E->getOpcode()) {
8552 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008553 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8554 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8555 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8556 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8557 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8558 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008559 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008560 }
8561 }
Richard Smith7bb00672012-02-01 01:42:44 +00008562
8563 if (LHSTy->isMemberPointerType()) {
8564 assert(E->isEqualityOp() && "unexpected member pointer operation");
8565 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8566
8567 MemberPtr LHSValue, RHSValue;
8568
8569 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008570 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008571 return false;
8572
8573 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8574 return false;
8575
8576 // C++11 [expr.eq]p2:
8577 // If both operands are null, they compare equal. Otherwise if only one is
8578 // null, they compare unequal.
8579 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8580 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8581 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8582 }
8583
8584 // Otherwise if either is a pointer to a virtual member function, the
8585 // result is unspecified.
8586 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8587 if (MD->isVirtual())
8588 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8589 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8590 if (MD->isVirtual())
8591 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8592
8593 // Otherwise they compare equal if and only if they would refer to the
8594 // same member of the same most derived object or the same subobject if
8595 // they were dereferenced with a hypothetical object of the associated
8596 // class type.
8597 bool Equal = LHSValue == RHSValue;
8598 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8599 }
8600
Richard Smithab44d9b2012-02-14 22:35:28 +00008601 if (LHSTy->isNullPtrType()) {
8602 assert(E->isComparisonOp() && "unexpected nullptr operation");
8603 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8604 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8605 // are compared, the result is true of the operator is <=, >= or ==, and
8606 // false otherwise.
8607 BinaryOperator::Opcode Opcode = E->getOpcode();
8608 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8609 }
8610
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008611 assert((!LHSTy->isIntegralOrEnumerationType() ||
8612 !RHSTy->isIntegralOrEnumerationType()) &&
8613 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8614 // We can't continue from here for non-integral types.
8615 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008616}
8617
Peter Collingbournee190dee2011-03-11 19:24:49 +00008618/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8619/// a result as the expression's type.
8620bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8621 const UnaryExprOrTypeTraitExpr *E) {
8622 switch(E->getKind()) {
8623 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008624 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008625 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008626 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008627 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008628 }
Eli Friedman64004332009-03-23 04:38:34 +00008629
Peter Collingbournee190dee2011-03-11 19:24:49 +00008630 case UETT_VecStep: {
8631 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008632
Peter Collingbournee190dee2011-03-11 19:24:49 +00008633 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008634 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008635
Peter Collingbournee190dee2011-03-11 19:24:49 +00008636 // The vec_step built-in functions that take a 3-component
8637 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8638 if (n == 3)
8639 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008640
Peter Collingbournee190dee2011-03-11 19:24:49 +00008641 return Success(n, E);
8642 } else
8643 return Success(1, E);
8644 }
8645
8646 case UETT_SizeOf: {
8647 QualType SrcTy = E->getTypeOfArgument();
8648 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8649 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008650 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8651 SrcTy = Ref->getPointeeType();
8652
Richard Smithd62306a2011-11-10 06:34:14 +00008653 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008654 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008655 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008656 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008657 }
Alexey Bataev00396512015-07-02 03:40:19 +00008658 case UETT_OpenMPRequiredSimdAlign:
8659 assert(E->isArgumentType());
8660 return Success(
8661 Info.Ctx.toCharUnitsFromBits(
8662 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8663 .getQuantity(),
8664 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008665 }
8666
8667 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008668}
8669
Peter Collingbournee9200682011-05-13 03:29:01 +00008670bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008671 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008672 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008673 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008674 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008675 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008676 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008677 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008678 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008679 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008680 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008681 APSInt IdxResult;
8682 if (!EvaluateInteger(Idx, IdxResult, Info))
8683 return false;
8684 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8685 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008686 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008687 CurrentType = AT->getElementType();
8688 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8689 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008690 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008691 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008692
James Y Knight7281c352015-12-29 22:31:18 +00008693 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008694 FieldDecl *MemberDecl = ON.getField();
8695 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008696 if (!RT)
8697 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008698 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008699 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008700 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008701 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008702 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008703 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008704 CurrentType = MemberDecl->getType().getNonReferenceType();
8705 break;
8706 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008707
James Y Knight7281c352015-12-29 22:31:18 +00008708 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008709 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008710
James Y Knight7281c352015-12-29 22:31:18 +00008711 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008712 CXXBaseSpecifier *BaseSpec = ON.getBase();
8713 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008714 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008715
8716 // Find the layout of the class whose base we are looking into.
8717 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008718 if (!RT)
8719 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008720 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008721 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008722 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8723
8724 // Find the base class itself.
8725 CurrentType = BaseSpec->getType();
8726 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8727 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008728 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008729
8730 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008731 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008732 break;
8733 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008734 }
8735 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008736 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008737}
8738
Chris Lattnere13042c2008-07-11 19:10:17 +00008739bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008740 switch (E->getOpcode()) {
8741 default:
8742 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8743 // See C99 6.6p3.
8744 return Error(E);
8745 case UO_Extension:
8746 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8747 // If so, we could clear the diagnostic ID.
8748 return Visit(E->getSubExpr());
8749 case UO_Plus:
8750 // The result is just the value.
8751 return Visit(E->getSubExpr());
8752 case UO_Minus: {
8753 if (!Visit(E->getSubExpr()))
8754 return false;
8755 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008756 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008757 if (Value.isSigned() && Value.isMinSignedValue() &&
8758 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8759 E->getType()))
8760 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008761 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008762 }
8763 case UO_Not: {
8764 if (!Visit(E->getSubExpr()))
8765 return false;
8766 if (!Result.isInt()) return Error(E);
8767 return Success(~Result.getInt(), E);
8768 }
8769 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008770 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008771 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008772 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008773 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008774 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008775 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008776}
Mike Stump11289f42009-09-09 15:08:12 +00008777
Chris Lattner477c4be2008-07-12 01:15:53 +00008778/// HandleCast - This is used to evaluate implicit or explicit casts where the
8779/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008780bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8781 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008782 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008783 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008784
Eli Friedmanc757de22011-03-25 00:43:55 +00008785 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008786 case CK_BaseToDerived:
8787 case CK_DerivedToBase:
8788 case CK_UncheckedDerivedToBase:
8789 case CK_Dynamic:
8790 case CK_ToUnion:
8791 case CK_ArrayToPointerDecay:
8792 case CK_FunctionToPointerDecay:
8793 case CK_NullToPointer:
8794 case CK_NullToMemberPointer:
8795 case CK_BaseToDerivedMemberPointer:
8796 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008797 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008798 case CK_ConstructorConversion:
8799 case CK_IntegralToPointer:
8800 case CK_ToVoid:
8801 case CK_VectorSplat:
8802 case CK_IntegralToFloating:
8803 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008804 case CK_CPointerToObjCPointerCast:
8805 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008806 case CK_AnyPointerToBlockPointerCast:
8807 case CK_ObjCObjectLValueCast:
8808 case CK_FloatingRealToComplex:
8809 case CK_FloatingComplexToReal:
8810 case CK_FloatingComplexCast:
8811 case CK_FloatingComplexToIntegralComplex:
8812 case CK_IntegralRealToComplex:
8813 case CK_IntegralComplexCast:
8814 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008815 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008816 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008817 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008818 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008819 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008820 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008821 llvm_unreachable("invalid cast kind for integral value");
8822
Eli Friedman9faf2f92011-03-25 19:07:11 +00008823 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008824 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008825 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008826 case CK_ARCProduceObject:
8827 case CK_ARCConsumeObject:
8828 case CK_ARCReclaimReturnedObject:
8829 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008830 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008831 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008832
Richard Smith4ef685b2012-01-17 21:17:26 +00008833 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008834 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008835 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008836 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008837 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008838
8839 case CK_MemberPointerToBoolean:
8840 case CK_PointerToBoolean:
8841 case CK_IntegralToBoolean:
8842 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008843 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008844 case CK_FloatingComplexToBoolean:
8845 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008846 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008847 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008848 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008849 uint64_t IntResult = BoolResult;
8850 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8851 IntResult = (uint64_t)-1;
8852 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008853 }
8854
Eli Friedmanc757de22011-03-25 00:43:55 +00008855 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008856 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008857 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008858
Eli Friedman742421e2009-02-20 01:15:07 +00008859 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008860 // Allow casts of address-of-label differences if they are no-ops
8861 // or narrowing. (The narrowing case isn't actually guaranteed to
8862 // be constant-evaluatable except in some narrow cases which are hard
8863 // to detect here. We let it through on the assumption the user knows
8864 // what they are doing.)
8865 if (Result.isAddrLabelDiff())
8866 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008867 // Only allow casts of lvalues if they are lossless.
8868 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8869 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008870
Richard Smith911e1422012-01-30 22:27:01 +00008871 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8872 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008873 }
Mike Stump11289f42009-09-09 15:08:12 +00008874
Eli Friedmanc757de22011-03-25 00:43:55 +00008875 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008876 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8877
John McCall45d55e42010-05-07 21:00:08 +00008878 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008879 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008880 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008881
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008882 if (LV.getLValueBase()) {
8883 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008884 // FIXME: Allow a larger integer size than the pointer size, and allow
8885 // narrowing back down to pointer width in subsequent integral casts.
8886 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008887 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008888 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008889
Richard Smithcf74da72011-11-16 07:18:12 +00008890 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008891 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008892 return true;
8893 }
8894
Yaxun Liu402804b2016-12-15 08:09:08 +00008895 uint64_t V;
8896 if (LV.isNullPointer())
8897 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8898 else
8899 V = LV.getLValueOffset().getQuantity();
8900
8901 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008902 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008903 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008904
Eli Friedmanc757de22011-03-25 00:43:55 +00008905 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008906 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008907 if (!EvaluateComplex(SubExpr, C, Info))
8908 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008909 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008910 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008911
Eli Friedmanc757de22011-03-25 00:43:55 +00008912 case CK_FloatingToIntegral: {
8913 APFloat F(0.0);
8914 if (!EvaluateFloat(SubExpr, F, Info))
8915 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008916
Richard Smith357362d2011-12-13 06:39:58 +00008917 APSInt Value;
8918 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8919 return false;
8920 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008921 }
8922 }
Mike Stump11289f42009-09-09 15:08:12 +00008923
Eli Friedmanc757de22011-03-25 00:43:55 +00008924 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008925}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008926
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008927bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8928 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008929 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008930 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8931 return false;
8932 if (!LV.isComplexInt())
8933 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008934 return Success(LV.getComplexIntReal(), E);
8935 }
8936
8937 return Visit(E->getSubExpr());
8938}
8939
Eli Friedman4e7a2412009-02-27 04:45:43 +00008940bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008941 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008942 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008943 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8944 return false;
8945 if (!LV.isComplexInt())
8946 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008947 return Success(LV.getComplexIntImag(), E);
8948 }
8949
Richard Smith4a678122011-10-24 18:44:57 +00008950 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008951 return Success(0, E);
8952}
8953
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008954bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8955 return Success(E->getPackLength(), E);
8956}
8957
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008958bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8959 return Success(E->getValue(), E);
8960}
8961
Chris Lattner05706e882008-07-11 18:11:29 +00008962//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008963// Float Evaluation
8964//===----------------------------------------------------------------------===//
8965
8966namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008967class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008968 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008969 APFloat &Result;
8970public:
8971 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008972 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008973
Richard Smith2e312c82012-03-03 22:46:17 +00008974 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008975 Result = V.getFloat();
8976 return true;
8977 }
Eli Friedman24c01542008-08-22 00:06:13 +00008978
Richard Smithfddd3842011-12-30 21:15:51 +00008979 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008980 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8981 return true;
8982 }
8983
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008984 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008985
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008986 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008987 bool VisitBinaryOperator(const BinaryOperator *E);
8988 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008989 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008990
John McCallb1fb0d32010-05-07 22:08:54 +00008991 bool VisitUnaryReal(const UnaryOperator *E);
8992 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008993
Richard Smithfddd3842011-12-30 21:15:51 +00008994 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008995};
8996} // end anonymous namespace
8997
8998static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008999 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009000 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009001}
9002
Jay Foad39c79802011-01-12 09:06:06 +00009003static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009004 QualType ResultTy,
9005 const Expr *Arg,
9006 bool SNaN,
9007 llvm::APFloat &Result) {
9008 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9009 if (!S) return false;
9010
9011 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9012
9013 llvm::APInt fill;
9014
9015 // Treat empty strings as if they were zero.
9016 if (S->getString().empty())
9017 fill = llvm::APInt(32, 0);
9018 else if (S->getString().getAsInteger(0, fill))
9019 return false;
9020
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009021 if (Context.getTargetInfo().isNan2008()) {
9022 if (SNaN)
9023 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9024 else
9025 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9026 } else {
9027 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9028 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9029 // a different encoding to what became a standard in 2008, and for pre-
9030 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9031 // sNaN. This is now known as "legacy NaN" encoding.
9032 if (SNaN)
9033 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9034 else
9035 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9036 }
9037
John McCall16291492010-02-28 13:00:19 +00009038 return true;
9039}
9040
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009041bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009042 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009043 default:
9044 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9045
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009046 case Builtin::BI__builtin_huge_val:
9047 case Builtin::BI__builtin_huge_valf:
9048 case Builtin::BI__builtin_huge_vall:
9049 case Builtin::BI__builtin_inf:
9050 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009051 case Builtin::BI__builtin_infl: {
9052 const llvm::fltSemantics &Sem =
9053 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009054 Result = llvm::APFloat::getInf(Sem);
9055 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009056 }
Mike Stump11289f42009-09-09 15:08:12 +00009057
John McCall16291492010-02-28 13:00:19 +00009058 case Builtin::BI__builtin_nans:
9059 case Builtin::BI__builtin_nansf:
9060 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009061 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9062 true, Result))
9063 return Error(E);
9064 return true;
John McCall16291492010-02-28 13:00:19 +00009065
Chris Lattner0b7282e2008-10-06 06:31:58 +00009066 case Builtin::BI__builtin_nan:
9067 case Builtin::BI__builtin_nanf:
9068 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00009069 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009070 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009071 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9072 false, Result))
9073 return Error(E);
9074 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009075
9076 case Builtin::BI__builtin_fabs:
9077 case Builtin::BI__builtin_fabsf:
9078 case Builtin::BI__builtin_fabsl:
9079 if (!EvaluateFloat(E->getArg(0), Result, Info))
9080 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009081
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009082 if (Result.isNegative())
9083 Result.changeSign();
9084 return true;
9085
Richard Smith8889a3d2013-06-13 06:26:32 +00009086 // FIXME: Builtin::BI__builtin_powi
9087 // FIXME: Builtin::BI__builtin_powif
9088 // FIXME: Builtin::BI__builtin_powil
9089
Mike Stump11289f42009-09-09 15:08:12 +00009090 case Builtin::BI__builtin_copysign:
9091 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009092 case Builtin::BI__builtin_copysignl: {
9093 APFloat RHS(0.);
9094 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9095 !EvaluateFloat(E->getArg(1), RHS, Info))
9096 return false;
9097 Result.copySign(RHS);
9098 return true;
9099 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009100 }
9101}
9102
John McCallb1fb0d32010-05-07 22:08:54 +00009103bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009104 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9105 ComplexValue CV;
9106 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9107 return false;
9108 Result = CV.FloatReal;
9109 return true;
9110 }
9111
9112 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009113}
9114
9115bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009116 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9117 ComplexValue CV;
9118 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9119 return false;
9120 Result = CV.FloatImag;
9121 return true;
9122 }
9123
Richard Smith4a678122011-10-24 18:44:57 +00009124 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009125 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9126 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009127 return true;
9128}
9129
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009130bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009131 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009132 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009133 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009134 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009135 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009136 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9137 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009138 Result.changeSign();
9139 return true;
9140 }
9141}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009142
Eli Friedman24c01542008-08-22 00:06:13 +00009143bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009144 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9145 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009146
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009147 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009148 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009149 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009150 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009151 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9152 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009153}
9154
9155bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9156 Result = E->getValue();
9157 return true;
9158}
9159
Peter Collingbournee9200682011-05-13 03:29:01 +00009160bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9161 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009162
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009163 switch (E->getCastKind()) {
9164 default:
Richard Smith11562c52011-10-28 17:51:58 +00009165 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009166
9167 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009168 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009169 return EvaluateInteger(SubExpr, IntResult, Info) &&
9170 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9171 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009172 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009173
9174 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009175 if (!Visit(SubExpr))
9176 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009177 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9178 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009179 }
John McCalld7646252010-11-14 08:17:51 +00009180
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009181 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009182 ComplexValue V;
9183 if (!EvaluateComplex(SubExpr, V, Info))
9184 return false;
9185 Result = V.getComplexFloatReal();
9186 return true;
9187 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009188 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009189}
9190
Eli Friedman24c01542008-08-22 00:06:13 +00009191//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009192// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009193//===----------------------------------------------------------------------===//
9194
9195namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009196class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009197 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009198 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009199
Anders Carlsson537969c2008-11-16 20:27:53 +00009200public:
John McCall93d91dc2010-05-07 17:22:02 +00009201 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009202 : ExprEvaluatorBaseTy(info), Result(Result) {}
9203
Richard Smith2e312c82012-03-03 22:46:17 +00009204 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009205 Result.setFrom(V);
9206 return true;
9207 }
Mike Stump11289f42009-09-09 15:08:12 +00009208
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009209 bool ZeroInitialization(const Expr *E);
9210
Anders Carlsson537969c2008-11-16 20:27:53 +00009211 //===--------------------------------------------------------------------===//
9212 // Visitor Methods
9213 //===--------------------------------------------------------------------===//
9214
Peter Collingbournee9200682011-05-13 03:29:01 +00009215 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009216 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009217 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009218 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009219 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009220};
9221} // end anonymous namespace
9222
John McCall93d91dc2010-05-07 17:22:02 +00009223static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9224 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009225 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009226 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009227}
9228
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009229bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009230 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009231 if (ElemTy->isRealFloatingType()) {
9232 Result.makeComplexFloat();
9233 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9234 Result.FloatReal = Zero;
9235 Result.FloatImag = Zero;
9236 } else {
9237 Result.makeComplexInt();
9238 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9239 Result.IntReal = Zero;
9240 Result.IntImag = Zero;
9241 }
9242 return true;
9243}
9244
Peter Collingbournee9200682011-05-13 03:29:01 +00009245bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9246 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009247
9248 if (SubExpr->getType()->isRealFloatingType()) {
9249 Result.makeComplexFloat();
9250 APFloat &Imag = Result.FloatImag;
9251 if (!EvaluateFloat(SubExpr, Imag, Info))
9252 return false;
9253
9254 Result.FloatReal = APFloat(Imag.getSemantics());
9255 return true;
9256 } else {
9257 assert(SubExpr->getType()->isIntegerType() &&
9258 "Unexpected imaginary literal.");
9259
9260 Result.makeComplexInt();
9261 APSInt &Imag = Result.IntImag;
9262 if (!EvaluateInteger(SubExpr, Imag, Info))
9263 return false;
9264
9265 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9266 return true;
9267 }
9268}
9269
Peter Collingbournee9200682011-05-13 03:29:01 +00009270bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009271
John McCallfcef3cf2010-12-14 17:51:41 +00009272 switch (E->getCastKind()) {
9273 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009274 case CK_BaseToDerived:
9275 case CK_DerivedToBase:
9276 case CK_UncheckedDerivedToBase:
9277 case CK_Dynamic:
9278 case CK_ToUnion:
9279 case CK_ArrayToPointerDecay:
9280 case CK_FunctionToPointerDecay:
9281 case CK_NullToPointer:
9282 case CK_NullToMemberPointer:
9283 case CK_BaseToDerivedMemberPointer:
9284 case CK_DerivedToBaseMemberPointer:
9285 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009286 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009287 case CK_ConstructorConversion:
9288 case CK_IntegralToPointer:
9289 case CK_PointerToIntegral:
9290 case CK_PointerToBoolean:
9291 case CK_ToVoid:
9292 case CK_VectorSplat:
9293 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009294 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009295 case CK_IntegralToBoolean:
9296 case CK_IntegralToFloating:
9297 case CK_FloatingToIntegral:
9298 case CK_FloatingToBoolean:
9299 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009300 case CK_CPointerToObjCPointerCast:
9301 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009302 case CK_AnyPointerToBlockPointerCast:
9303 case CK_ObjCObjectLValueCast:
9304 case CK_FloatingComplexToReal:
9305 case CK_FloatingComplexToBoolean:
9306 case CK_IntegralComplexToReal:
9307 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009308 case CK_ARCProduceObject:
9309 case CK_ARCConsumeObject:
9310 case CK_ARCReclaimReturnedObject:
9311 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009312 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009313 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009314 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009315 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009316 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009317 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009318 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009319 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009320
John McCallfcef3cf2010-12-14 17:51:41 +00009321 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009322 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009323 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009324 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009325
9326 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009327 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009328 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009329 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009330
9331 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009332 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009333 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009334 return false;
9335
John McCallfcef3cf2010-12-14 17:51:41 +00009336 Result.makeComplexFloat();
9337 Result.FloatImag = APFloat(Real.getSemantics());
9338 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009339 }
9340
John McCallfcef3cf2010-12-14 17:51:41 +00009341 case CK_FloatingComplexCast: {
9342 if (!Visit(E->getSubExpr()))
9343 return false;
9344
9345 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9346 QualType From
9347 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9348
Richard Smith357362d2011-12-13 06:39:58 +00009349 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9350 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009351 }
9352
9353 case CK_FloatingComplexToIntegralComplex: {
9354 if (!Visit(E->getSubExpr()))
9355 return false;
9356
9357 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9358 QualType From
9359 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9360 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009361 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9362 To, Result.IntReal) &&
9363 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9364 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009365 }
9366
9367 case CK_IntegralRealToComplex: {
9368 APSInt &Real = Result.IntReal;
9369 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9370 return false;
9371
9372 Result.makeComplexInt();
9373 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9374 return true;
9375 }
9376
9377 case CK_IntegralComplexCast: {
9378 if (!Visit(E->getSubExpr()))
9379 return false;
9380
9381 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9382 QualType From
9383 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9384
Richard Smith911e1422012-01-30 22:27:01 +00009385 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9386 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009387 return true;
9388 }
9389
9390 case CK_IntegralComplexToFloatingComplex: {
9391 if (!Visit(E->getSubExpr()))
9392 return false;
9393
Ted Kremenek28831752012-08-23 20:46:57 +00009394 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009395 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009396 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009397 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009398 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9399 To, Result.FloatReal) &&
9400 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9401 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009402 }
9403 }
9404
9405 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009406}
9407
John McCall93d91dc2010-05-07 17:22:02 +00009408bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009409 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009410 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9411
Chandler Carrutha216cad2014-10-11 00:57:18 +00009412 // Track whether the LHS or RHS is real at the type system level. When this is
9413 // the case we can simplify our evaluation strategy.
9414 bool LHSReal = false, RHSReal = false;
9415
9416 bool LHSOK;
9417 if (E->getLHS()->getType()->isRealFloatingType()) {
9418 LHSReal = true;
9419 APFloat &Real = Result.FloatReal;
9420 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9421 if (LHSOK) {
9422 Result.makeComplexFloat();
9423 Result.FloatImag = APFloat(Real.getSemantics());
9424 }
9425 } else {
9426 LHSOK = Visit(E->getLHS());
9427 }
George Burgess IVa145e252016-05-25 22:38:36 +00009428 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009429 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009430
John McCall93d91dc2010-05-07 17:22:02 +00009431 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009432 if (E->getRHS()->getType()->isRealFloatingType()) {
9433 RHSReal = true;
9434 APFloat &Real = RHS.FloatReal;
9435 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9436 return false;
9437 RHS.makeComplexFloat();
9438 RHS.FloatImag = APFloat(Real.getSemantics());
9439 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009440 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009441
Chandler Carrutha216cad2014-10-11 00:57:18 +00009442 assert(!(LHSReal && RHSReal) &&
9443 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009444 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009445 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009446 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009447 if (Result.isComplexFloat()) {
9448 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9449 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009450 if (LHSReal)
9451 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9452 else if (!RHSReal)
9453 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9454 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009455 } else {
9456 Result.getComplexIntReal() += RHS.getComplexIntReal();
9457 Result.getComplexIntImag() += RHS.getComplexIntImag();
9458 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009459 break;
John McCalle3027922010-08-25 11:45:40 +00009460 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009461 if (Result.isComplexFloat()) {
9462 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9463 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009464 if (LHSReal) {
9465 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9466 Result.getComplexFloatImag().changeSign();
9467 } else if (!RHSReal) {
9468 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9469 APFloat::rmNearestTiesToEven);
9470 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009471 } else {
9472 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9473 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9474 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009475 break;
John McCalle3027922010-08-25 11:45:40 +00009476 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009477 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009478 // This is an implementation of complex multiplication according to the
9479 // constraints laid out in C11 Annex G. The implemantion uses the
9480 // following naming scheme:
9481 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009482 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009483 APFloat &A = LHS.getComplexFloatReal();
9484 APFloat &B = LHS.getComplexFloatImag();
9485 APFloat &C = RHS.getComplexFloatReal();
9486 APFloat &D = RHS.getComplexFloatImag();
9487 APFloat &ResR = Result.getComplexFloatReal();
9488 APFloat &ResI = Result.getComplexFloatImag();
9489 if (LHSReal) {
9490 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9491 ResR = A * C;
9492 ResI = A * D;
9493 } else if (RHSReal) {
9494 ResR = C * A;
9495 ResI = C * B;
9496 } else {
9497 // In the fully general case, we need to handle NaNs and infinities
9498 // robustly.
9499 APFloat AC = A * C;
9500 APFloat BD = B * D;
9501 APFloat AD = A * D;
9502 APFloat BC = B * C;
9503 ResR = AC - BD;
9504 ResI = AD + BC;
9505 if (ResR.isNaN() && ResI.isNaN()) {
9506 bool Recalc = false;
9507 if (A.isInfinity() || B.isInfinity()) {
9508 A = APFloat::copySign(
9509 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9510 B = APFloat::copySign(
9511 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9512 if (C.isNaN())
9513 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9514 if (D.isNaN())
9515 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9516 Recalc = true;
9517 }
9518 if (C.isInfinity() || D.isInfinity()) {
9519 C = APFloat::copySign(
9520 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9521 D = APFloat::copySign(
9522 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9523 if (A.isNaN())
9524 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9525 if (B.isNaN())
9526 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9527 Recalc = true;
9528 }
9529 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9530 AD.isInfinity() || BC.isInfinity())) {
9531 if (A.isNaN())
9532 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9533 if (B.isNaN())
9534 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9535 if (C.isNaN())
9536 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9537 if (D.isNaN())
9538 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9539 Recalc = true;
9540 }
9541 if (Recalc) {
9542 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9543 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9544 }
9545 }
9546 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009547 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009548 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009549 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009550 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9551 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009552 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009553 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9554 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9555 }
9556 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009557 case BO_Div:
9558 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009559 // This is an implementation of complex division according to the
9560 // constraints laid out in C11 Annex G. The implemantion uses the
9561 // following naming scheme:
9562 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009563 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009564 APFloat &A = LHS.getComplexFloatReal();
9565 APFloat &B = LHS.getComplexFloatImag();
9566 APFloat &C = RHS.getComplexFloatReal();
9567 APFloat &D = RHS.getComplexFloatImag();
9568 APFloat &ResR = Result.getComplexFloatReal();
9569 APFloat &ResI = Result.getComplexFloatImag();
9570 if (RHSReal) {
9571 ResR = A / C;
9572 ResI = B / C;
9573 } else {
9574 if (LHSReal) {
9575 // No real optimizations we can do here, stub out with zero.
9576 B = APFloat::getZero(A.getSemantics());
9577 }
9578 int DenomLogB = 0;
9579 APFloat MaxCD = maxnum(abs(C), abs(D));
9580 if (MaxCD.isFinite()) {
9581 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009582 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9583 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009584 }
9585 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009586 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9587 APFloat::rmNearestTiesToEven);
9588 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9589 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009590 if (ResR.isNaN() && ResI.isNaN()) {
9591 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9592 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9593 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9594 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9595 D.isFinite()) {
9596 A = APFloat::copySign(
9597 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9598 B = APFloat::copySign(
9599 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9600 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9601 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9602 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9603 C = APFloat::copySign(
9604 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9605 D = APFloat::copySign(
9606 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9607 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9608 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9609 }
9610 }
9611 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009612 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009613 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9614 return Error(E, diag::note_expr_divide_by_zero);
9615
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009616 ComplexValue LHS = Result;
9617 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9618 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9619 Result.getComplexIntReal() =
9620 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9621 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9622 Result.getComplexIntImag() =
9623 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9624 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9625 }
9626 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009627 }
9628
John McCall93d91dc2010-05-07 17:22:02 +00009629 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009630}
9631
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009632bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9633 // Get the operand value into 'Result'.
9634 if (!Visit(E->getSubExpr()))
9635 return false;
9636
9637 switch (E->getOpcode()) {
9638 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009639 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009640 case UO_Extension:
9641 return true;
9642 case UO_Plus:
9643 // The result is always just the subexpr.
9644 return true;
9645 case UO_Minus:
9646 if (Result.isComplexFloat()) {
9647 Result.getComplexFloatReal().changeSign();
9648 Result.getComplexFloatImag().changeSign();
9649 }
9650 else {
9651 Result.getComplexIntReal() = -Result.getComplexIntReal();
9652 Result.getComplexIntImag() = -Result.getComplexIntImag();
9653 }
9654 return true;
9655 case UO_Not:
9656 if (Result.isComplexFloat())
9657 Result.getComplexFloatImag().changeSign();
9658 else
9659 Result.getComplexIntImag() = -Result.getComplexIntImag();
9660 return true;
9661 }
9662}
9663
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009664bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9665 if (E->getNumInits() == 2) {
9666 if (E->getType()->isComplexType()) {
9667 Result.makeComplexFloat();
9668 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9669 return false;
9670 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9671 return false;
9672 } else {
9673 Result.makeComplexInt();
9674 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9675 return false;
9676 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9677 return false;
9678 }
9679 return true;
9680 }
9681 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9682}
9683
Anders Carlsson537969c2008-11-16 20:27:53 +00009684//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009685// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9686// implicit conversion.
9687//===----------------------------------------------------------------------===//
9688
9689namespace {
9690class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009691 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00009692 APValue &Result;
9693public:
9694 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
9695 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9696
9697 bool Success(const APValue &V, const Expr *E) {
9698 Result = V;
9699 return true;
9700 }
9701
9702 bool ZeroInitialization(const Expr *E) {
9703 ImplicitValueInitExpr VIE(
9704 E->getType()->castAs<AtomicType>()->getValueType());
9705 return Evaluate(Result, Info, &VIE);
9706 }
9707
9708 bool VisitCastExpr(const CastExpr *E) {
9709 switch (E->getCastKind()) {
9710 default:
9711 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9712 case CK_NonAtomicToAtomic:
9713 return Evaluate(Result, Info, E->getSubExpr());
9714 }
9715 }
9716};
9717} // end anonymous namespace
9718
9719static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
9720 assert(E->isRValue() && E->getType()->isAtomicType());
9721 return AtomicExprEvaluator(Info, Result).Visit(E);
9722}
9723
9724//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009725// Void expression evaluation, primarily for a cast to void on the LHS of a
9726// comma operator
9727//===----------------------------------------------------------------------===//
9728
9729namespace {
9730class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009731 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009732public:
9733 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9734
Richard Smith2e312c82012-03-03 22:46:17 +00009735 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009736
9737 bool VisitCastExpr(const CastExpr *E) {
9738 switch (E->getCastKind()) {
9739 default:
9740 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9741 case CK_ToVoid:
9742 VisitIgnoredValue(E->getSubExpr());
9743 return true;
9744 }
9745 }
Hal Finkela8443c32014-07-17 14:49:58 +00009746
9747 bool VisitCallExpr(const CallExpr *E) {
9748 switch (E->getBuiltinCallee()) {
9749 default:
9750 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9751 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009752 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009753 // The argument is not evaluated!
9754 return true;
9755 }
9756 }
Richard Smith42d3af92011-12-07 00:43:50 +00009757};
9758} // end anonymous namespace
9759
9760static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9761 assert(E->isRValue() && E->getType()->isVoidType());
9762 return VoidExprEvaluator(Info).Visit(E);
9763}
9764
9765//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009766// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009767//===----------------------------------------------------------------------===//
9768
Richard Smith2e312c82012-03-03 22:46:17 +00009769static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009770 // In C, function designators are not lvalues, but we evaluate them as if they
9771 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009772 QualType T = E->getType();
9773 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009774 LValue LV;
9775 if (!EvaluateLValue(E, LV, Info))
9776 return false;
9777 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009778 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009779 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009780 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009781 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009782 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009783 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009784 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009785 LValue LV;
9786 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009787 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009788 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009789 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009790 llvm::APFloat F(0.0);
9791 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009792 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009793 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009794 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009795 ComplexValue C;
9796 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009797 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009798 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009799 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009800 MemberPtr P;
9801 if (!EvaluateMemberPointer(E, P, Info))
9802 return false;
9803 P.moveInto(Result);
9804 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009805 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009806 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009807 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009808 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9809 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009810 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009811 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009812 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009813 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009814 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009815 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9816 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009817 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009818 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009819 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009820 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009821 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009822 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009823 if (!EvaluateVoid(E, Info))
9824 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009825 } else if (T->isAtomicType()) {
9826 if (!EvaluateAtomic(E, Result, Info))
9827 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009828 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009829 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009830 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009831 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009832 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009833 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009834 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009835
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009836 return true;
9837}
9838
Richard Smithb228a862012-02-15 02:18:13 +00009839/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9840/// cases, the in-place evaluation is essential, since later initializers for
9841/// an object can indirectly refer to subobjects which were initialized earlier.
9842static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009843 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009844 assert(!E->isValueDependent());
9845
Richard Smith7525ff62013-05-09 07:14:00 +00009846 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009847 return false;
9848
9849 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009850 // Evaluate arrays and record types in-place, so that later initializers can
9851 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00009852 if (E->getType()->isArrayType())
9853 return EvaluateArray(E, This, Result, Info);
9854 else if (E->getType()->isRecordType())
9855 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00009856 }
9857
9858 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009859 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009860}
9861
Richard Smithf57d8cb2011-12-09 22:58:01 +00009862/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9863/// lvalue-to-rvalue cast if it is an lvalue.
9864static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009865 if (E->getType().isNull())
9866 return false;
9867
Richard Smithfddd3842011-12-30 21:15:51 +00009868 if (!CheckLiteralType(Info, E))
9869 return false;
9870
Richard Smith2e312c82012-03-03 22:46:17 +00009871 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009872 return false;
9873
9874 if (E->isGLValue()) {
9875 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009876 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009877 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009878 return false;
9879 }
9880
Richard Smith2e312c82012-03-03 22:46:17 +00009881 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009882 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009883}
Richard Smith11562c52011-10-28 17:51:58 +00009884
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009885static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9886 const ASTContext &Ctx, bool &IsConst) {
9887 // Fast-path evaluations of integer literals, since we sometimes see files
9888 // containing vast quantities of these.
9889 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9890 Result.Val = APValue(APSInt(L->getValue(),
9891 L->getType()->isUnsignedIntegerType()));
9892 IsConst = true;
9893 return true;
9894 }
James Dennett0492ef02014-03-14 17:44:10 +00009895
9896 // This case should be rare, but we need to check it before we check on
9897 // the type below.
9898 if (Exp->getType().isNull()) {
9899 IsConst = false;
9900 return true;
9901 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009902
9903 // FIXME: Evaluating values of large array and record types can cause
9904 // performance problems. Only do so in C++11 for now.
9905 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9906 Exp->getType()->isRecordType()) &&
9907 !Ctx.getLangOpts().CPlusPlus11) {
9908 IsConst = false;
9909 return true;
9910 }
9911 return false;
9912}
9913
9914
Richard Smith7b553f12011-10-29 00:50:52 +00009915/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009916/// any crazy technique (that has nothing to do with language standards) that
9917/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009918/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9919/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009920bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009921 bool IsConst;
9922 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9923 return IsConst;
9924
Richard Smith6d4c6582013-11-05 22:18:15 +00009925 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009926 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009927}
9928
Jay Foad39c79802011-01-12 09:06:06 +00009929bool Expr::EvaluateAsBooleanCondition(bool &Result,
9930 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009931 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009932 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009933 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009934}
9935
Richard Smithce8eca52015-12-08 03:21:47 +00009936static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9937 Expr::SideEffectsKind SEK) {
9938 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9939 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9940}
9941
Richard Smith5fab0c92011-12-28 19:48:30 +00009942bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9943 SideEffectsKind AllowSideEffects) const {
9944 if (!getType()->isIntegralOrEnumerationType())
9945 return false;
9946
Richard Smith11562c52011-10-28 17:51:58 +00009947 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009948 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009949 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009950 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009951
Richard Smith11562c52011-10-28 17:51:58 +00009952 Result = ExprResult.Val.getInt();
9953 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009954}
9955
Richard Trieube234c32016-04-21 21:04:55 +00009956bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9957 SideEffectsKind AllowSideEffects) const {
9958 if (!getType()->isRealFloatingType())
9959 return false;
9960
9961 EvalResult ExprResult;
9962 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9963 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9964 return false;
9965
9966 Result = ExprResult.Val.getFloat();
9967 return true;
9968}
9969
Jay Foad39c79802011-01-12 09:06:06 +00009970bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009971 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009972
John McCall45d55e42010-05-07 21:00:08 +00009973 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009974 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9975 !CheckLValueConstantExpression(Info, getExprLoc(),
9976 Ctx.getLValueReferenceType(getType()), LV))
9977 return false;
9978
Richard Smith2e312c82012-03-03 22:46:17 +00009979 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009980 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009981}
9982
Richard Smithd0b4dd62011-12-19 06:19:21 +00009983bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9984 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009985 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009986 // FIXME: Evaluating initializers for large array and record types can cause
9987 // performance problems. Only do so in C++11 for now.
9988 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009989 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009990 return false;
9991
Richard Smithd0b4dd62011-12-19 06:19:21 +00009992 Expr::EvalStatus EStatus;
9993 EStatus.Diag = &Notes;
9994
Richard Smith0c6124b2015-12-03 01:36:22 +00009995 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9996 ? EvalInfo::EM_ConstantExpression
9997 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009998 InitInfo.setEvaluatingDecl(VD, Value);
9999
10000 LValue LVal;
10001 LVal.set(VD);
10002
Richard Smithfddd3842011-12-30 21:15:51 +000010003 // C++11 [basic.start.init]p2:
10004 // Variables with static storage duration or thread storage duration shall be
10005 // zero-initialized before any other initialization takes place.
10006 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010007 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010008 !VD->getType()->isReferenceType()) {
10009 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010010 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010011 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010012 return false;
10013 }
10014
Richard Smith7525ff62013-05-09 07:14:00 +000010015 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10016 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010017 EStatus.HasSideEffects)
10018 return false;
10019
10020 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10021 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010022}
10023
Richard Smith7b553f12011-10-29 00:50:52 +000010024/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10025/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010026bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010027 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010028 return EvaluateAsRValue(Result, Ctx) &&
10029 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010030}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010031
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010032APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010033 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010034 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010035 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010036 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010037 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010038 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010039 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010040
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010041 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010042}
John McCall864e3962010-05-07 05:32:02 +000010043
Richard Smithe9ff7702013-11-05 22:23:30 +000010044void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010045 bool IsConst;
10046 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010047 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010048 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010049 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10050 }
10051}
10052
Richard Smithe6c01442013-06-05 00:46:14 +000010053bool Expr::EvalResult::isGlobalLValue() const {
10054 assert(Val.isLValue());
10055 return IsGlobalLValue(Val.getLValueBase());
10056}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010057
10058
John McCall864e3962010-05-07 05:32:02 +000010059/// isIntegerConstantExpr - this recursive routine will test if an expression is
10060/// an integer constant expression.
10061
10062/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10063/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010064
10065// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010066// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10067// and a (possibly null) SourceLocation indicating the location of the problem.
10068//
John McCall864e3962010-05-07 05:32:02 +000010069// Note that to reduce code duplication, this helper does no evaluation
10070// itself; the caller checks whether the expression is evaluatable, and
10071// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010072// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010073
Dan Gohman28ade552010-07-26 21:25:24 +000010074namespace {
10075
Richard Smith9e575da2012-12-28 13:25:52 +000010076enum ICEKind {
10077 /// This expression is an ICE.
10078 IK_ICE,
10079 /// This expression is not an ICE, but if it isn't evaluated, it's
10080 /// a legal subexpression for an ICE. This return value is used to handle
10081 /// the comma operator in C99 mode, and non-constant subexpressions.
10082 IK_ICEIfUnevaluated,
10083 /// This expression is not an ICE, and is not a legal subexpression for one.
10084 IK_NotICE
10085};
10086
John McCall864e3962010-05-07 05:32:02 +000010087struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010088 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010089 SourceLocation Loc;
10090
Richard Smith9e575da2012-12-28 13:25:52 +000010091 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010092};
10093
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010094}
Dan Gohman28ade552010-07-26 21:25:24 +000010095
Richard Smith9e575da2012-12-28 13:25:52 +000010096static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10097
10098static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010099
Craig Toppera31a8822013-08-22 07:09:37 +000010100static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010101 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010102 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010103 !EVResult.Val.isInt())
10104 return ICEDiag(IK_NotICE, E->getLocStart());
10105
John McCall864e3962010-05-07 05:32:02 +000010106 return NoDiag();
10107}
10108
Craig Toppera31a8822013-08-22 07:09:37 +000010109static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010110 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010111 if (!E->getType()->isIntegralOrEnumerationType())
10112 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010113
10114 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010115#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010116#define STMT(Node, Base) case Expr::Node##Class:
10117#define EXPR(Node, Base)
10118#include "clang/AST/StmtNodes.inc"
10119 case Expr::PredefinedExprClass:
10120 case Expr::FloatingLiteralClass:
10121 case Expr::ImaginaryLiteralClass:
10122 case Expr::StringLiteralClass:
10123 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010124 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010125 case Expr::MemberExprClass:
10126 case Expr::CompoundAssignOperatorClass:
10127 case Expr::CompoundLiteralExprClass:
10128 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010129 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010130 case Expr::ArrayInitLoopExprClass:
10131 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010132 case Expr::NoInitExprClass:
10133 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010134 case Expr::ImplicitValueInitExprClass:
10135 case Expr::ParenListExprClass:
10136 case Expr::VAArgExprClass:
10137 case Expr::AddrLabelExprClass:
10138 case Expr::StmtExprClass:
10139 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010140 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010141 case Expr::CXXDynamicCastExprClass:
10142 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010143 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010144 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010145 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010146 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010147 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010148 case Expr::CXXThisExprClass:
10149 case Expr::CXXThrowExprClass:
10150 case Expr::CXXNewExprClass:
10151 case Expr::CXXDeleteExprClass:
10152 case Expr::CXXPseudoDestructorExprClass:
10153 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010154 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010155 case Expr::DependentScopeDeclRefExprClass:
10156 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010157 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010158 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010159 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010160 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010161 case Expr::CXXTemporaryObjectExprClass:
10162 case Expr::CXXUnresolvedConstructExprClass:
10163 case Expr::CXXDependentScopeMemberExprClass:
10164 case Expr::UnresolvedMemberExprClass:
10165 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010166 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010167 case Expr::ObjCArrayLiteralClass:
10168 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010169 case Expr::ObjCEncodeExprClass:
10170 case Expr::ObjCMessageExprClass:
10171 case Expr::ObjCSelectorExprClass:
10172 case Expr::ObjCProtocolExprClass:
10173 case Expr::ObjCIvarRefExprClass:
10174 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010175 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010176 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010177 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010178 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010179 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010180 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010181 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010182 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010183 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010184 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010185 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010186 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010187 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010188 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010189 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010190 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010191 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010192 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010193 case Expr::CoawaitExprClass:
10194 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010195 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010196
Richard Smithf137f932014-01-25 20:50:08 +000010197 case Expr::InitListExprClass: {
10198 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10199 // form "T x = { a };" is equivalent to "T x = a;".
10200 // Unless we're initializing a reference, T is a scalar as it is known to be
10201 // of integral or enumeration type.
10202 if (E->isRValue())
10203 if (cast<InitListExpr>(E)->getNumInits() == 1)
10204 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10205 return ICEDiag(IK_NotICE, E->getLocStart());
10206 }
10207
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010208 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010209 case Expr::GNUNullExprClass:
10210 // GCC considers the GNU __null value to be an integral constant expression.
10211 return NoDiag();
10212
John McCall7c454bb2011-07-15 05:09:51 +000010213 case Expr::SubstNonTypeTemplateParmExprClass:
10214 return
10215 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10216
John McCall864e3962010-05-07 05:32:02 +000010217 case Expr::ParenExprClass:
10218 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010219 case Expr::GenericSelectionExprClass:
10220 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010221 case Expr::IntegerLiteralClass:
10222 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010223 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010224 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010225 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010226 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010227 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010228 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010229 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010230 return NoDiag();
10231 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010232 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010233 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10234 // constant expressions, but they can never be ICEs because an ICE cannot
10235 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010236 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010237 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010238 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010239 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010240 }
Richard Smith6365c912012-02-24 22:12:32 +000010241 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010242 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10243 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010244 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010245 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010246 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010247 // Parameter variables are never constants. Without this check,
10248 // getAnyInitializer() can find a default argument, which leads
10249 // to chaos.
10250 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010251 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010252
10253 // C++ 7.1.5.1p2
10254 // A variable of non-volatile const-qualified integral or enumeration
10255 // type initialized by an ICE can be used in ICEs.
10256 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010257 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010258 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010259
Richard Smithd0b4dd62011-12-19 06:19:21 +000010260 const VarDecl *VD;
10261 // Look for a declaration of this variable that has an initializer, and
10262 // check whether it is an ICE.
10263 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10264 return NoDiag();
10265 else
Richard Smith9e575da2012-12-28 13:25:52 +000010266 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010267 }
10268 }
Richard Smith9e575da2012-12-28 13:25:52 +000010269 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010270 }
John McCall864e3962010-05-07 05:32:02 +000010271 case Expr::UnaryOperatorClass: {
10272 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10273 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010274 case UO_PostInc:
10275 case UO_PostDec:
10276 case UO_PreInc:
10277 case UO_PreDec:
10278 case UO_AddrOf:
10279 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010280 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010281 // C99 6.6/3 allows increment and decrement within unevaluated
10282 // subexpressions of constant expressions, but they can never be ICEs
10283 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010284 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010285 case UO_Extension:
10286 case UO_LNot:
10287 case UO_Plus:
10288 case UO_Minus:
10289 case UO_Not:
10290 case UO_Real:
10291 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010292 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010293 }
Richard Smith9e575da2012-12-28 13:25:52 +000010294
John McCall864e3962010-05-07 05:32:02 +000010295 // OffsetOf falls through here.
10296 }
10297 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010298 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10299 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10300 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10301 // compliance: we should warn earlier for offsetof expressions with
10302 // array subscripts that aren't ICEs, and if the array subscripts
10303 // are ICEs, the value of the offsetof must be an integer constant.
10304 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010305 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010306 case Expr::UnaryExprOrTypeTraitExprClass: {
10307 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10308 if ((Exp->getKind() == UETT_SizeOf) &&
10309 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010310 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010311 return NoDiag();
10312 }
10313 case Expr::BinaryOperatorClass: {
10314 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10315 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010316 case BO_PtrMemD:
10317 case BO_PtrMemI:
10318 case BO_Assign:
10319 case BO_MulAssign:
10320 case BO_DivAssign:
10321 case BO_RemAssign:
10322 case BO_AddAssign:
10323 case BO_SubAssign:
10324 case BO_ShlAssign:
10325 case BO_ShrAssign:
10326 case BO_AndAssign:
10327 case BO_XorAssign:
10328 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000010329 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10330 // constant expressions, but they can never be ICEs because an ICE cannot
10331 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010332 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010333
John McCalle3027922010-08-25 11:45:40 +000010334 case BO_Mul:
10335 case BO_Div:
10336 case BO_Rem:
10337 case BO_Add:
10338 case BO_Sub:
10339 case BO_Shl:
10340 case BO_Shr:
10341 case BO_LT:
10342 case BO_GT:
10343 case BO_LE:
10344 case BO_GE:
10345 case BO_EQ:
10346 case BO_NE:
10347 case BO_And:
10348 case BO_Xor:
10349 case BO_Or:
10350 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010351 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10352 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010353 if (Exp->getOpcode() == BO_Div ||
10354 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010355 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010356 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010357 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010358 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010359 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010360 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010361 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010362 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010363 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010364 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010365 }
10366 }
10367 }
John McCalle3027922010-08-25 11:45:40 +000010368 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010369 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010370 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10371 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010372 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10373 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010374 } else {
10375 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010376 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010377 }
10378 }
Richard Smith9e575da2012-12-28 13:25:52 +000010379 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010380 }
John McCalle3027922010-08-25 11:45:40 +000010381 case BO_LAnd:
10382 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010383 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10384 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010385 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010386 // Rare case where the RHS has a comma "side-effect"; we need
10387 // to actually check the condition to see whether the side
10388 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010389 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010390 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010391 return RHSResult;
10392 return NoDiag();
10393 }
10394
Richard Smith9e575da2012-12-28 13:25:52 +000010395 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010396 }
10397 }
10398 }
10399 case Expr::ImplicitCastExprClass:
10400 case Expr::CStyleCastExprClass:
10401 case Expr::CXXFunctionalCastExprClass:
10402 case Expr::CXXStaticCastExprClass:
10403 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010404 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010405 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010406 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010407 if (isa<ExplicitCastExpr>(E)) {
10408 if (const FloatingLiteral *FL
10409 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10410 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10411 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10412 APSInt IgnoredVal(DestWidth, !DestSigned);
10413 bool Ignored;
10414 // If the value does not fit in the destination type, the behavior is
10415 // undefined, so we are not required to treat it as a constant
10416 // expression.
10417 if (FL->getValue().convertToInteger(IgnoredVal,
10418 llvm::APFloat::rmTowardZero,
10419 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010420 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010421 return NoDiag();
10422 }
10423 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010424 switch (cast<CastExpr>(E)->getCastKind()) {
10425 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010426 case CK_AtomicToNonAtomic:
10427 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010428 case CK_NoOp:
10429 case CK_IntegralToBoolean:
10430 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010431 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010432 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010433 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010434 }
John McCall864e3962010-05-07 05:32:02 +000010435 }
John McCallc07a0c72011-02-17 10:25:35 +000010436 case Expr::BinaryConditionalOperatorClass: {
10437 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10438 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010439 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010440 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010441 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10442 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10443 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010444 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010445 return FalseResult;
10446 }
John McCall864e3962010-05-07 05:32:02 +000010447 case Expr::ConditionalOperatorClass: {
10448 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10449 // If the condition (ignoring parens) is a __builtin_constant_p call,
10450 // then only the true side is actually considered in an integer constant
10451 // expression, and it is fully evaluated. This is an important GNU
10452 // extension. See GCC PR38377 for discussion.
10453 if (const CallExpr *CallCE
10454 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010455 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010456 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010457 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010458 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010459 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010460
Richard Smithf57d8cb2011-12-09 22:58:01 +000010461 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10462 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010463
Richard Smith9e575da2012-12-28 13:25:52 +000010464 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010465 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010466 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010467 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010468 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010469 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010470 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010471 return NoDiag();
10472 // Rare case where the diagnostics depend on which side is evaluated
10473 // Note that if we get here, CondResult is 0, and at least one of
10474 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010475 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010476 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010477 return TrueResult;
10478 }
10479 case Expr::CXXDefaultArgExprClass:
10480 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010481 case Expr::CXXDefaultInitExprClass:
10482 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010483 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010484 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010485 }
10486 }
10487
David Blaikiee4d798f2012-01-20 21:50:17 +000010488 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010489}
10490
Richard Smithf57d8cb2011-12-09 22:58:01 +000010491/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010492static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010493 const Expr *E,
10494 llvm::APSInt *Value,
10495 SourceLocation *Loc) {
10496 if (!E->getType()->isIntegralOrEnumerationType()) {
10497 if (Loc) *Loc = E->getExprLoc();
10498 return false;
10499 }
10500
Richard Smith66e05fe2012-01-18 05:21:49 +000010501 APValue Result;
10502 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010503 return false;
10504
Richard Smith98710fc2014-11-13 23:03:19 +000010505 if (!Result.isInt()) {
10506 if (Loc) *Loc = E->getExprLoc();
10507 return false;
10508 }
10509
Richard Smith66e05fe2012-01-18 05:21:49 +000010510 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010511 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010512}
10513
Craig Toppera31a8822013-08-22 07:09:37 +000010514bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10515 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010516 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010517 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010518
Richard Smith9e575da2012-12-28 13:25:52 +000010519 ICEDiag D = CheckICE(this, Ctx);
10520 if (D.Kind != IK_ICE) {
10521 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010522 return false;
10523 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010524 return true;
10525}
10526
Craig Toppera31a8822013-08-22 07:09:37 +000010527bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010528 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010529 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010530 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10531
10532 if (!isIntegerConstantExpr(Ctx, Loc))
10533 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010534 // The only possible side-effects here are due to UB discovered in the
10535 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10536 // required to treat the expression as an ICE, so we produce the folded
10537 // value.
10538 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010539 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010540 return true;
10541}
Richard Smith66e05fe2012-01-18 05:21:49 +000010542
Craig Toppera31a8822013-08-22 07:09:37 +000010543bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010544 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010545}
10546
Craig Toppera31a8822013-08-22 07:09:37 +000010547bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010548 SourceLocation *Loc) const {
10549 // We support this checking in C++98 mode in order to diagnose compatibility
10550 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010551 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010552
Richard Smith98a0a492012-02-14 21:38:30 +000010553 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010554 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010555 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010556 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010557 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010558
10559 APValue Scratch;
10560 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10561
10562 if (!Diags.empty()) {
10563 IsConstExpr = false;
10564 if (Loc) *Loc = Diags[0].first;
10565 } else if (!IsConstExpr) {
10566 // FIXME: This shouldn't happen.
10567 if (Loc) *Loc = getExprLoc();
10568 }
10569
10570 return IsConstExpr;
10571}
Richard Smith253c2a32012-01-27 01:14:48 +000010572
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010573bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10574 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010575 ArrayRef<const Expr*> Args,
10576 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010577 Expr::EvalStatus Status;
10578 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10579
George Burgess IV177399e2017-01-09 04:12:14 +000010580 LValue ThisVal;
10581 const LValue *ThisPtr = nullptr;
10582 if (This) {
10583#ifndef NDEBUG
10584 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10585 assert(MD && "Don't provide `this` for non-methods.");
10586 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10587#endif
10588 if (EvaluateObjectArgument(Info, This, ThisVal))
10589 ThisPtr = &ThisVal;
10590 if (Info.EvalStatus.HasSideEffects)
10591 return false;
10592 }
10593
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010594 ArgVector ArgValues(Args.size());
10595 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10596 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010597 if ((*I)->isValueDependent() ||
10598 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010599 // If evaluation fails, throw away the argument entirely.
10600 ArgValues[I - Args.begin()] = APValue();
10601 if (Info.EvalStatus.HasSideEffects)
10602 return false;
10603 }
10604
10605 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010606 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010607 ArgValues.data());
10608 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10609}
10610
Richard Smith253c2a32012-01-27 01:14:48 +000010611bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010612 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010613 PartialDiagnosticAt> &Diags) {
10614 // FIXME: It would be useful to check constexpr function templates, but at the
10615 // moment the constant expression evaluator cannot cope with the non-rigorous
10616 // ASTs which we build for dependent expressions.
10617 if (FD->isDependentContext())
10618 return true;
10619
10620 Expr::EvalStatus Status;
10621 Status.Diag = &Diags;
10622
Richard Smith6d4c6582013-11-05 22:18:15 +000010623 EvalInfo Info(FD->getASTContext(), Status,
10624 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010625
10626 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010627 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010628
Richard Smith7525ff62013-05-09 07:14:00 +000010629 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010630 // is a temporary being used as the 'this' pointer.
10631 LValue This;
10632 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010633 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010634
Richard Smith253c2a32012-01-27 01:14:48 +000010635 ArrayRef<const Expr*> Args;
10636
Richard Smith2e312c82012-03-03 22:46:17 +000010637 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010638 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10639 // Evaluate the call as a constant initializer, to allow the construction
10640 // of objects of non-literal types.
10641 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010642 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10643 } else {
10644 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010645 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010646 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010647 }
Richard Smith253c2a32012-01-27 01:14:48 +000010648
10649 return Diags.empty();
10650}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010651
10652bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10653 const FunctionDecl *FD,
10654 SmallVectorImpl<
10655 PartialDiagnosticAt> &Diags) {
10656 Expr::EvalStatus Status;
10657 Status.Diag = &Diags;
10658
10659 EvalInfo Info(FD->getASTContext(), Status,
10660 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10661
10662 // Fabricate a call stack frame to give the arguments a plausible cover story.
10663 ArrayRef<const Expr*> Args;
10664 ArgVector ArgValues(0);
10665 bool Success = EvaluateArgs(Args, ArgValues, Info);
10666 (void)Success;
10667 assert(Success &&
10668 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010669 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010670
10671 APValue ResultScratch;
10672 Evaluate(ResultScratch, Info, E);
10673 return Diags.empty();
10674}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010675
10676bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10677 unsigned Type) const {
10678 if (!getType()->isPointerType())
10679 return false;
10680
10681 Expr::EvalStatus Status;
10682 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010683 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010684}