blob: dff126db0c2ff820da2b9b06a3d44ba8471a74d0 [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
Richard Smithf6f003a2011-12-16 19:06:07 +0000428 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
429 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000430 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000431 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000432
433 APValue *getTemporary(const void *Key) {
434 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000435 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000436 }
437 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000438 };
439
Richard Smith852c9db2013-04-20 22:23:05 +0000440 /// Temporarily override 'this'.
441 class ThisOverrideRAII {
442 public:
443 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
444 : Frame(Frame), OldThis(Frame.This) {
445 if (Enable)
446 Frame.This = NewThis;
447 }
448 ~ThisOverrideRAII() {
449 Frame.This = OldThis;
450 }
451 private:
452 CallStackFrame &Frame;
453 const LValue *OldThis;
454 };
455
Richard Smith92b1ce02011-12-12 09:28:41 +0000456 /// A partial diagnostic which we might know in advance that we are not going
457 /// to emit.
458 class OptionalDiagnostic {
459 PartialDiagnostic *Diag;
460
461 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000462 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
463 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000464
465 template<typename T>
466 OptionalDiagnostic &operator<<(const T &v) {
467 if (Diag)
468 *Diag << v;
469 return *this;
470 }
Richard Smithfe800032012-01-31 04:08:20 +0000471
472 OptionalDiagnostic &operator<<(const APSInt &I) {
473 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000474 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000475 I.toString(Buffer);
476 *Diag << StringRef(Buffer.data(), Buffer.size());
477 }
478 return *this;
479 }
480
481 OptionalDiagnostic &operator<<(const APFloat &F) {
482 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000483 // FIXME: Force the precision of the source value down so we don't
484 // print digits which are usually useless (we don't really care here if
485 // we truncate a digit by accident in edge cases). Ideally,
486 // APFloat::toString would automatically print the shortest
487 // representation which rounds to the correct value, but it's a bit
488 // tricky to implement.
489 unsigned precision =
490 llvm::APFloat::semanticsPrecision(F.getSemantics());
491 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000492 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000493 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000494 *Diag << StringRef(Buffer.data(), Buffer.size());
495 }
496 return *this;
497 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000498 };
499
Richard Smith08d6a2c2013-07-24 07:11:57 +0000500 /// A cleanup, and a flag indicating whether it is lifetime-extended.
501 class Cleanup {
502 llvm::PointerIntPair<APValue*, 1, bool> Value;
503
504 public:
505 Cleanup(APValue *Val, bool IsLifetimeExtended)
506 : Value(Val, IsLifetimeExtended) {}
507
508 bool isLifetimeExtended() const { return Value.getInt(); }
509 void endLifetime() {
510 *Value.getPointer() = APValue();
511 }
512 };
513
Richard Smithb228a862012-02-15 02:18:13 +0000514 /// EvalInfo - This is a private struct used by the evaluator to capture
515 /// information about a subexpression as it is folded. It retains information
516 /// about the AST context, but also maintains information about the folded
517 /// expression.
518 ///
519 /// If an expression could be evaluated, it is still possible it is not a C
520 /// "integer constant expression" or constant expression. If not, this struct
521 /// captures information about how and why not.
522 ///
523 /// One bit of information passed *into* the request for constant folding
524 /// indicates whether the subexpression is "evaluated" or not according to C
525 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
526 /// evaluate the expression regardless of what the RHS is, but C only allows
527 /// certain things in certain situations.
Reid Kleckner06df4022016-12-13 19:48:32 +0000528 struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000529 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000530
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000531 /// EvalStatus - Contains information about the evaluation.
532 Expr::EvalStatus &EvalStatus;
533
534 /// CurrentCall - The top of the constexpr call stack.
535 CallStackFrame *CurrentCall;
536
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000537 /// CallStackDepth - The number of calls in the call stack right now.
538 unsigned CallStackDepth;
539
Richard Smithb228a862012-02-15 02:18:13 +0000540 /// NextCallIndex - The next call index to assign.
541 unsigned NextCallIndex;
542
Richard Smitha3d3bd22013-05-08 02:12:03 +0000543 /// StepsLeft - The remaining number of evaluation steps we're permitted
544 /// to perform. This is essentially a limit for the number of statements
545 /// we will evaluate.
546 unsigned StepsLeft;
547
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000548 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000549 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000550 CallStackFrame BottomFrame;
551
Richard Smith08d6a2c2013-07-24 07:11:57 +0000552 /// A stack of values whose lifetimes end at the end of some surrounding
553 /// evaluation frame.
554 llvm::SmallVector<Cleanup, 16> CleanupStack;
555
Richard Smithd62306a2011-11-10 06:34:14 +0000556 /// EvaluatingDecl - This is the declaration whose initializer is being
557 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000558 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000559
560 /// EvaluatingDeclValue - This is the value being constructed for the
561 /// declaration whose initializer is being evaluated, if any.
562 APValue *EvaluatingDeclValue;
563
Richard Smith410306b2016-12-12 02:53:20 +0000564 /// The current array initialization index, if we're performing array
565 /// initialization.
566 uint64_t ArrayInitIndex = -1;
567
Richard Smith357362d2011-12-13 06:39:58 +0000568 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
569 /// notes attached to it will also be stored, otherwise they will not be.
570 bool HasActiveDiagnostic;
571
Richard Smith0c6124b2015-12-03 01:36:22 +0000572 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
573 /// fold (not just why it's not strictly a constant expression)?
574 bool HasFoldFailureDiagnostic;
575
George Burgess IV8c892b52016-05-25 22:31:54 +0000576 /// \brief Whether or not we're currently speculatively evaluating.
577 bool IsSpeculativelyEvaluating;
578
Richard Smith6d4c6582013-11-05 22:18:15 +0000579 enum EvaluationMode {
580 /// Evaluate as a constant expression. Stop if we find that the expression
581 /// is not a constant expression.
582 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000583
Richard Smith6d4c6582013-11-05 22:18:15 +0000584 /// Evaluate as a potential constant expression. Keep going if we hit a
585 /// construct that we can't evaluate yet (because we don't yet know the
586 /// value of something) but stop if we hit something that could never be
587 /// a constant expression.
588 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000589
Richard Smith6d4c6582013-11-05 22:18:15 +0000590 /// Fold the expression to a constant. Stop if we hit a side-effect that
591 /// we can't model.
592 EM_ConstantFold,
593
594 /// Evaluate the expression looking for integer overflow and similar
595 /// issues. Don't worry about side-effects, and try to visit all
596 /// subexpressions.
597 EM_EvaluateForOverflow,
598
599 /// Evaluate in any way we know how. Don't worry about side-effects that
600 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000601 EM_IgnoreSideEffects,
602
603 /// Evaluate as a constant expression. Stop if we find that the expression
604 /// is not a constant expression. Some expressions can be retried in the
605 /// optimizer if we don't constant fold them here, but in an unevaluated
606 /// context we try to fold them immediately since the optimizer never
607 /// gets a chance to look at it.
608 EM_ConstantExpressionUnevaluated,
609
610 /// Evaluate as a potential constant expression. Keep going if we hit a
611 /// construct that we can't evaluate yet (because we don't yet know the
612 /// value of something) but stop if we hit something that could never be
613 /// a constant expression. Some expressions can be retried in the
614 /// optimizer if we don't constant fold them here, but in an unevaluated
615 /// context we try to fold them immediately since the optimizer never
616 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000617 EM_PotentialConstantExpressionUnevaluated,
618
George Burgess IVf9013bf2017-02-10 22:52:29 +0000619 /// Evaluate as a constant expression. In certain scenarios, if:
620 /// - we find a MemberExpr with a base that can't be evaluated, or
621 /// - we find a variable initialized with a call to a function that has
622 /// the alloc_size attribute on it
623 /// then we may consider evaluation to have succeeded.
624 ///
George Burgess IVe3763372016-12-22 02:50:20 +0000625 /// In either case, the LValue returned shall have an invalid base; in the
626 /// former, the base will be the invalid MemberExpr, in the latter, the
627 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
628 /// said CallExpr.
629 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000630 } EvalMode;
631
632 /// Are we checking whether the expression is a potential constant
633 /// expression?
634 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000635 return EvalMode == EM_PotentialConstantExpression ||
636 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000637 }
638
639 /// Are we checking an expression for overflow?
640 // FIXME: We should check for any kind of undefined or suspicious behavior
641 // in such constructs, not just overflow.
642 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
643
644 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000645 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000646 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000647 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000648 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
649 EvaluatingDecl((const ValueDecl *)nullptr),
650 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000651 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
652 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000653
Richard Smith7525ff62013-05-09 07:14:00 +0000654 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
655 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000656 EvaluatingDeclValue = &Value;
657 }
658
David Blaikiebbafb8a2012-03-11 07:00:24 +0000659 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000660
Richard Smith357362d2011-12-13 06:39:58 +0000661 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000662 // Don't perform any constexpr calls (other than the call we're checking)
663 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000664 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000665 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000666 if (NextCallIndex == 0) {
667 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000668 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000669 return false;
670 }
Richard Smith357362d2011-12-13 06:39:58 +0000671 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
672 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000673 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000674 << getLangOpts().ConstexprCallDepth;
675 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000676 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000677
Richard Smithb228a862012-02-15 02:18:13 +0000678 CallStackFrame *getCallFrame(unsigned CallIndex) {
679 assert(CallIndex && "no call index in getCallFrame");
680 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
681 // be null in this loop.
682 CallStackFrame *Frame = CurrentCall;
683 while (Frame->Index > CallIndex)
684 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000685 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000686 }
687
Richard Smitha3d3bd22013-05-08 02:12:03 +0000688 bool nextStep(const Stmt *S) {
689 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000690 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000691 return false;
692 }
693 --StepsLeft;
694 return true;
695 }
696
Richard Smith357362d2011-12-13 06:39:58 +0000697 private:
698 /// Add a diagnostic to the diagnostics list.
699 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
700 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
701 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
702 return EvalStatus.Diag->back().second;
703 }
704
Richard Smithf6f003a2011-12-16 19:06:07 +0000705 /// Add notes containing a call stack to the current point of evaluation.
706 void addCallStack(unsigned Limit);
707
Faisal Valie690b7a2016-07-02 22:34:24 +0000708 private:
709 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
710 unsigned ExtraNotes, bool IsCCEDiag) {
711
Richard Smith92b1ce02011-12-12 09:28:41 +0000712 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000713 // If we have a prior diagnostic, it will be noting that the expression
714 // isn't a constant expression. This diagnostic is more important,
715 // unless we require this evaluation to produce a constant expression.
716 //
717 // FIXME: We might want to show both diagnostics to the user in
718 // EM_ConstantFold mode.
719 if (!EvalStatus.Diag->empty()) {
720 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000721 case EM_ConstantFold:
722 case EM_IgnoreSideEffects:
723 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000724 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000725 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000726 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000727 case EM_ConstantExpression:
728 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000729 case EM_ConstantExpressionUnevaluated:
730 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000731 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000732 HasActiveDiagnostic = false;
733 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000734 }
735 }
736
Richard Smithf6f003a2011-12-16 19:06:07 +0000737 unsigned CallStackNotes = CallStackDepth - 1;
738 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
739 if (Limit)
740 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000741 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000742 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000743
Richard Smith357362d2011-12-13 06:39:58 +0000744 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000745 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000746 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000747 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
748 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000749 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000750 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000751 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000752 }
Richard Smith357362d2011-12-13 06:39:58 +0000753 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000754 return OptionalDiagnostic();
755 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000756 public:
757 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
758 OptionalDiagnostic
759 FFDiag(SourceLocation Loc,
760 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
761 unsigned ExtraNotes = 0) {
762 return Diag(Loc, DiagId, ExtraNotes, false);
763 }
764
765 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000766 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000767 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000768 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000769 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000770 HasActiveDiagnostic = false;
771 return OptionalDiagnostic();
772 }
773
Richard Smith92b1ce02011-12-12 09:28:41 +0000774 /// Diagnose that the evaluation does not produce a C++11 core constant
775 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000776 ///
777 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
778 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000779 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000780 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000781 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000782 // Don't override a previous diagnostic. Don't bother collecting
783 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000784 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000785 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000786 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000787 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000788 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000789 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000790 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
791 = diag::note_invalid_subexpr_in_const_expr,
792 unsigned ExtraNotes = 0) {
793 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
794 }
Richard Smith357362d2011-12-13 06:39:58 +0000795 /// Add a note to a prior diagnostic.
796 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
797 if (!HasActiveDiagnostic)
798 return OptionalDiagnostic();
799 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000800 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000801
802 /// Add a stack of notes to a prior diagnostic.
803 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
804 if (HasActiveDiagnostic) {
805 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
806 Diags.begin(), Diags.end());
807 }
808 }
Richard Smith253c2a32012-01-27 01:14:48 +0000809
Richard Smith6d4c6582013-11-05 22:18:15 +0000810 /// Should we continue evaluation after encountering a side-effect that we
811 /// couldn't model?
812 bool keepEvaluatingAfterSideEffect() {
813 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000814 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000815 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000816 case EM_EvaluateForOverflow:
817 case EM_IgnoreSideEffects:
818 return true;
819
Richard Smith6d4c6582013-11-05 22:18:15 +0000820 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000821 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000822 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000823 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000824 return false;
825 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000826 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000827 }
828
829 /// Note that we have had a side-effect, and determine whether we should
830 /// keep evaluating.
831 bool noteSideEffect() {
832 EvalStatus.HasSideEffects = true;
833 return keepEvaluatingAfterSideEffect();
834 }
835
Richard Smithce8eca52015-12-08 03:21:47 +0000836 /// Should we continue evaluation after encountering undefined behavior?
837 bool keepEvaluatingAfterUndefinedBehavior() {
838 switch (EvalMode) {
839 case EM_EvaluateForOverflow:
840 case EM_IgnoreSideEffects:
841 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000842 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000843 return true;
844
845 case EM_PotentialConstantExpression:
846 case EM_PotentialConstantExpressionUnevaluated:
847 case EM_ConstantExpression:
848 case EM_ConstantExpressionUnevaluated:
849 return false;
850 }
851 llvm_unreachable("Missed EvalMode case");
852 }
853
854 /// Note that we hit something that was technically undefined behavior, but
855 /// that we can evaluate past it (such as signed overflow or floating-point
856 /// division by zero.)
857 bool noteUndefinedBehavior() {
858 EvalStatus.HasUndefinedBehavior = true;
859 return keepEvaluatingAfterUndefinedBehavior();
860 }
861
Richard Smith253c2a32012-01-27 01:14:48 +0000862 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000863 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000864 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000865 if (!StepsLeft)
866 return false;
867
868 switch (EvalMode) {
869 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000870 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000871 case EM_EvaluateForOverflow:
872 return true;
873
874 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000875 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000876 case EM_ConstantFold:
877 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000878 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000879 return false;
880 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000881 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000882 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000883
George Burgess IV8c892b52016-05-25 22:31:54 +0000884 /// Notes that we failed to evaluate an expression that other expressions
885 /// directly depend on, and determine if we should keep evaluating. This
886 /// should only be called if we actually intend to keep evaluating.
887 ///
888 /// Call noteSideEffect() instead if we may be able to ignore the value that
889 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
890 ///
891 /// (Foo(), 1) // use noteSideEffect
892 /// (Foo() || true) // use noteSideEffect
893 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000894 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000895 // Failure when evaluating some expression often means there is some
896 // subexpression whose evaluation was skipped. Therefore, (because we
897 // don't track whether we skipped an expression when unwinding after an
898 // evaluation failure) every evaluation failure that bubbles up from a
899 // subexpression implies that a side-effect has potentially happened. We
900 // skip setting the HasSideEffects flag to true until we decide to
901 // continue evaluating after that point, which happens here.
902 bool KeepGoing = keepEvaluatingAfterFailure();
903 EvalStatus.HasSideEffects |= KeepGoing;
904 return KeepGoing;
905 }
906
Richard Smith410306b2016-12-12 02:53:20 +0000907 class ArrayInitLoopIndex {
908 EvalInfo &Info;
909 uint64_t OuterIndex;
910
911 public:
912 ArrayInitLoopIndex(EvalInfo &Info)
913 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
914 Info.ArrayInitIndex = 0;
915 }
916 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
917
918 operator uint64_t&() { return Info.ArrayInitIndex; }
919 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000920 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000921
922 /// Object used to treat all foldable expressions as constant expressions.
923 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000924 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000925 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000926 bool HadNoPriorDiags;
927 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000928
Richard Smith6d4c6582013-11-05 22:18:15 +0000929 explicit FoldConstant(EvalInfo &Info, bool Enabled)
930 : Info(Info),
931 Enabled(Enabled),
932 HadNoPriorDiags(Info.EvalStatus.Diag &&
933 Info.EvalStatus.Diag->empty() &&
934 !Info.EvalStatus.HasSideEffects),
935 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000936 if (Enabled &&
937 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
938 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000939 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000940 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000941 void keepDiagnostics() { Enabled = false; }
942 ~FoldConstant() {
943 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000944 !Info.EvalStatus.HasSideEffects)
945 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000946 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000947 }
948 };
Richard Smith17100ba2012-02-16 02:46:34 +0000949
George Burgess IV3a03fab2015-09-04 21:28:13 +0000950 /// RAII object used to treat the current evaluation as the correct pointer
951 /// offset fold for the current EvalMode
952 struct FoldOffsetRAII {
953 EvalInfo &Info;
954 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +0000955 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +0000956 : Info(Info), OldMode(Info.EvalMode) {
957 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +0000958 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000959 }
960
961 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
962 };
963
George Burgess IV8c892b52016-05-25 22:31:54 +0000964 /// RAII object used to optionally suppress diagnostics and side-effects from
965 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000966 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000967 /// Pair of EvalInfo, and a bit that stores whether or not we were
968 /// speculatively evaluating when we created this RAII.
969 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000970 Expr::EvalStatus Old;
971
George Burgess IV8c892b52016-05-25 22:31:54 +0000972 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
973 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
974 Old = Other.Old;
975 Other.InfoAndOldSpecEval.setPointer(nullptr);
976 }
977
978 void maybeRestoreState() {
979 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
980 if (!Info)
981 return;
982
983 Info->EvalStatus = Old;
984 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
985 }
986
Richard Smith17100ba2012-02-16 02:46:34 +0000987 public:
George Burgess IV8c892b52016-05-25 22:31:54 +0000988 SpeculativeEvaluationRAII() = default;
989
990 SpeculativeEvaluationRAII(
991 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
992 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
993 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +0000994 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +0000995 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000996 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000997
998 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
999 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1000 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001001 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001002
1003 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1004 maybeRestoreState();
1005 moveFromAndCancel(std::move(Other));
1006 return *this;
1007 }
1008
1009 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001010 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001011
1012 /// RAII object wrapping a full-expression or block scope, and handling
1013 /// the ending of the lifetime of temporaries created within it.
1014 template<bool IsFullExpression>
1015 class ScopeRAII {
1016 EvalInfo &Info;
1017 unsigned OldStackSize;
1018 public:
1019 ScopeRAII(EvalInfo &Info)
1020 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1021 ~ScopeRAII() {
1022 // Body moved to a static method to encourage the compiler to inline away
1023 // instances of this class.
1024 cleanup(Info, OldStackSize);
1025 }
1026 private:
1027 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1028 unsigned NewEnd = OldStackSize;
1029 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1030 I != N; ++I) {
1031 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1032 // Full-expression cleanup of a lifetime-extended temporary: nothing
1033 // to do, just move this cleanup to the right place in the stack.
1034 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1035 ++NewEnd;
1036 } else {
1037 // End the lifetime of the object.
1038 Info.CleanupStack[I].endLifetime();
1039 }
1040 }
1041 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1042 Info.CleanupStack.end());
1043 }
1044 };
1045 typedef ScopeRAII<false> BlockScopeRAII;
1046 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001047}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001048
Richard Smitha8105bc2012-01-06 16:39:00 +00001049bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1050 CheckSubobjectKind CSK) {
1051 if (Invalid)
1052 return false;
1053 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001054 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001055 << CSK;
1056 setInvalid();
1057 return false;
1058 }
1059 return true;
1060}
1061
1062void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Richard Smithd6cc1982017-01-31 02:23:02 +00001063 const Expr *E, APSInt N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001064 // If we're complaining, we must be able to statically determine the size of
1065 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001066 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001067 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001068 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001069 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001070 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001071 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001072 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001073 setInvalid();
1074}
1075
Richard Smithf6f003a2011-12-16 19:06:07 +00001076CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1077 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001078 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001079 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1080 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001081 Info.CurrentCall = this;
1082 ++Info.CallStackDepth;
1083}
1084
1085CallStackFrame::~CallStackFrame() {
1086 assert(Info.CurrentCall == this && "calls retired out of order");
1087 --Info.CallStackDepth;
1088 Info.CurrentCall = Caller;
1089}
1090
Richard Smith08d6a2c2013-07-24 07:11:57 +00001091APValue &CallStackFrame::createTemporary(const void *Key,
1092 bool IsLifetimeExtended) {
1093 APValue &Result = Temporaries[Key];
1094 assert(Result.isUninit() && "temporary created multiple times");
1095 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1096 return Result;
1097}
1098
Richard Smith84401042013-06-03 05:03:02 +00001099static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001100
1101void EvalInfo::addCallStack(unsigned Limit) {
1102 // Determine which calls to skip, if any.
1103 unsigned ActiveCalls = CallStackDepth - 1;
1104 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1105 if (Limit && Limit < ActiveCalls) {
1106 SkipStart = Limit / 2 + Limit % 2;
1107 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001108 }
1109
Richard Smithf6f003a2011-12-16 19:06:07 +00001110 // Walk the call stack and add the diagnostics.
1111 unsigned CallIdx = 0;
1112 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1113 Frame = Frame->Caller, ++CallIdx) {
1114 // Skip this call?
1115 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1116 if (CallIdx == SkipStart) {
1117 // Note that we're skipping calls.
1118 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1119 << unsigned(ActiveCalls - Limit);
1120 }
1121 continue;
1122 }
1123
Richard Smith5179eb72016-06-28 19:03:57 +00001124 // Use a different note for an inheriting constructor, because from the
1125 // user's perspective it's not really a function at all.
1126 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1127 if (CD->isInheritingConstructor()) {
1128 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1129 << CD->getParent();
1130 continue;
1131 }
1132 }
1133
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001134 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001135 llvm::raw_svector_ostream Out(Buffer);
1136 describeCall(Frame, Out);
1137 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1138 }
1139}
1140
1141namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001142 struct ComplexValue {
1143 private:
1144 bool IsInt;
1145
1146 public:
1147 APSInt IntReal, IntImag;
1148 APFloat FloatReal, FloatImag;
1149
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001150 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001151
1152 void makeComplexFloat() { IsInt = false; }
1153 bool isComplexFloat() const { return !IsInt; }
1154 APFloat &getComplexFloatReal() { return FloatReal; }
1155 APFloat &getComplexFloatImag() { return FloatImag; }
1156
1157 void makeComplexInt() { IsInt = true; }
1158 bool isComplexInt() const { return IsInt; }
1159 APSInt &getComplexIntReal() { return IntReal; }
1160 APSInt &getComplexIntImag() { return IntImag; }
1161
Richard Smith2e312c82012-03-03 22:46:17 +00001162 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001163 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001164 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001165 else
Richard Smith2e312c82012-03-03 22:46:17 +00001166 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001167 }
Richard Smith2e312c82012-03-03 22:46:17 +00001168 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001169 assert(v.isComplexFloat() || v.isComplexInt());
1170 if (v.isComplexFloat()) {
1171 makeComplexFloat();
1172 FloatReal = v.getComplexFloatReal();
1173 FloatImag = v.getComplexFloatImag();
1174 } else {
1175 makeComplexInt();
1176 IntReal = v.getComplexIntReal();
1177 IntImag = v.getComplexIntImag();
1178 }
1179 }
John McCall93d91dc2010-05-07 17:22:02 +00001180 };
John McCall45d55e42010-05-07 21:00:08 +00001181
1182 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001183 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001184 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001185 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001186 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001187 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001188 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001189
Richard Smithce40ad62011-11-12 22:28:03 +00001190 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001191 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001192 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001193 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001194 SubobjectDesignator &getLValueDesignator() { return Designator; }
1195 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001196 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001197
Richard Smith2e312c82012-03-03 22:46:17 +00001198 void moveInto(APValue &V) const {
1199 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001200 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1201 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001202 else {
1203 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1204 assert(!Designator.FirstEntryIsAnUnsizedArray &&
1205 "Unsized array with a valid base?");
Richard Smith2e312c82012-03-03 22:46:17 +00001206 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001207 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001208 }
John McCall45d55e42010-05-07 21:00:08 +00001209 }
Richard Smith2e312c82012-03-03 22:46:17 +00001210 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001211 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001212 Base = V.getLValueBase();
1213 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001214 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001215 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001216 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001217 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001218 }
1219
Yaxun Liu402804b2016-12-15 08:09:08 +00001220 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
1221 bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
George Burgess IVe3763372016-12-22 02:50:20 +00001222#ifndef NDEBUG
1223 // We only allow a few types of invalid bases. Enforce that here.
1224 if (BInvalid) {
1225 const auto *E = B.get<const Expr *>();
1226 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1227 "Unexpected type of invalid base");
1228 }
1229#endif
1230
Richard Smithce40ad62011-11-12 22:28:03 +00001231 Base = B;
Yaxun Liu402804b2016-12-15 08:09:08 +00001232 Offset = CharUnits::fromQuantity(Offset_);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001233 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001234 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001235 Designator = SubobjectDesignator(getType(B));
Yaxun Liu402804b2016-12-15 08:09:08 +00001236 IsNullPtr = IsNullPtr_;
Richard Smitha8105bc2012-01-06 16:39:00 +00001237 }
1238
George Burgess IV3a03fab2015-09-04 21:28:13 +00001239 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1240 set(B, I, true);
1241 }
1242
Richard Smitha8105bc2012-01-06 16:39:00 +00001243 // Check that this LValue is not based on a null pointer. If it is, produce
1244 // a diagnostic and mark the designator as invalid.
1245 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1246 CheckSubobjectKind CSK) {
1247 if (Designator.Invalid)
1248 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001249 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001250 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001251 << CSK;
1252 Designator.setInvalid();
1253 return false;
1254 }
1255 return true;
1256 }
1257
1258 // Check this LValue refers to an object. If not, set the designator to be
1259 // invalid and emit a diagnostic.
1260 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001261 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001262 Designator.checkSubobject(Info, E, CSK);
1263 }
1264
1265 void addDecl(EvalInfo &Info, const Expr *E,
1266 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001267 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1268 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001269 }
George Burgess IVe3763372016-12-22 02:50:20 +00001270 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1271 assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1272 assert(isBaseAnAllocSizeCall(Base) &&
1273 "Only alloc_size bases can have unsized arrays");
1274 Designator.FirstEntryIsAnUnsizedArray = true;
1275 Designator.addUnsizedArrayUnchecked(ElemTy);
1276 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001277 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001278 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1279 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001280 }
Richard Smith66c96992012-02-18 22:04:06 +00001281 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001282 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1283 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001284 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001285 void clearIsNullPointer() {
1286 IsNullPtr = false;
1287 }
Richard Smithd6cc1982017-01-31 02:23:02 +00001288 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, APSInt Index,
Yaxun Liu402804b2016-12-15 08:09:08 +00001289 CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001290 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1291 // but we're not required to diagnose it and it's valid in C++.)
1292 if (!Index)
1293 return;
1294
1295 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1296 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1297 // offsets.
1298 uint64_t Offset64 = Offset.getQuantity();
1299 uint64_t ElemSize64 = ElementSize.getQuantity();
1300 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1301 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1302
1303 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001304 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001305 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001306 }
1307 void adjustOffset(CharUnits N) {
1308 Offset += N;
1309 if (N.getQuantity())
1310 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001311 }
John McCall45d55e42010-05-07 21:00:08 +00001312 };
Richard Smith027bf112011-11-17 22:56:20 +00001313
1314 struct MemberPtr {
1315 MemberPtr() {}
1316 explicit MemberPtr(const ValueDecl *Decl) :
1317 DeclAndIsDerivedMember(Decl, false), Path() {}
1318
1319 /// The member or (direct or indirect) field referred to by this member
1320 /// pointer, or 0 if this is a null member pointer.
1321 const ValueDecl *getDecl() const {
1322 return DeclAndIsDerivedMember.getPointer();
1323 }
1324 /// Is this actually a member of some type derived from the relevant class?
1325 bool isDerivedMember() const {
1326 return DeclAndIsDerivedMember.getInt();
1327 }
1328 /// Get the class which the declaration actually lives in.
1329 const CXXRecordDecl *getContainingRecord() const {
1330 return cast<CXXRecordDecl>(
1331 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1332 }
1333
Richard Smith2e312c82012-03-03 22:46:17 +00001334 void moveInto(APValue &V) const {
1335 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001336 }
Richard Smith2e312c82012-03-03 22:46:17 +00001337 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001338 assert(V.isMemberPointer());
1339 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1340 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1341 Path.clear();
1342 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1343 Path.insert(Path.end(), P.begin(), P.end());
1344 }
1345
1346 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1347 /// whether the member is a member of some class derived from the class type
1348 /// of the member pointer.
1349 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1350 /// Path - The path of base/derived classes from the member declaration's
1351 /// class (exclusive) to the class type of the member pointer (inclusive).
1352 SmallVector<const CXXRecordDecl*, 4> Path;
1353
1354 /// Perform a cast towards the class of the Decl (either up or down the
1355 /// hierarchy).
1356 bool castBack(const CXXRecordDecl *Class) {
1357 assert(!Path.empty());
1358 const CXXRecordDecl *Expected;
1359 if (Path.size() >= 2)
1360 Expected = Path[Path.size() - 2];
1361 else
1362 Expected = getContainingRecord();
1363 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1364 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1365 // if B does not contain the original member and is not a base or
1366 // derived class of the class containing the original member, the result
1367 // of the cast is undefined.
1368 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1369 // (D::*). We consider that to be a language defect.
1370 return false;
1371 }
1372 Path.pop_back();
1373 return true;
1374 }
1375 /// Perform a base-to-derived member pointer cast.
1376 bool castToDerived(const CXXRecordDecl *Derived) {
1377 if (!getDecl())
1378 return true;
1379 if (!isDerivedMember()) {
1380 Path.push_back(Derived);
1381 return true;
1382 }
1383 if (!castBack(Derived))
1384 return false;
1385 if (Path.empty())
1386 DeclAndIsDerivedMember.setInt(false);
1387 return true;
1388 }
1389 /// Perform a derived-to-base member pointer cast.
1390 bool castToBase(const CXXRecordDecl *Base) {
1391 if (!getDecl())
1392 return true;
1393 if (Path.empty())
1394 DeclAndIsDerivedMember.setInt(true);
1395 if (isDerivedMember()) {
1396 Path.push_back(Base);
1397 return true;
1398 }
1399 return castBack(Base);
1400 }
1401 };
Richard Smith357362d2011-12-13 06:39:58 +00001402
Richard Smith7bb00672012-02-01 01:42:44 +00001403 /// Compare two member pointers, which are assumed to be of the same type.
1404 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1405 if (!LHS.getDecl() || !RHS.getDecl())
1406 return !LHS.getDecl() && !RHS.getDecl();
1407 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1408 return false;
1409 return LHS.Path == RHS.Path;
1410 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001411}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001412
Richard Smith2e312c82012-03-03 22:46:17 +00001413static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001414static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1415 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001416 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001417static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1418 bool InvalidBaseOK = false);
1419static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1420 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001421static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1422 EvalInfo &Info);
1423static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001424static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001425static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001426 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001427static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001428static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001429static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001430static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001431
1432//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001433// Misc utilities
1434//===----------------------------------------------------------------------===//
1435
Richard Smithd6cc1982017-01-31 02:23:02 +00001436/// Negate an APSInt in place, converting it to a signed form if necessary, and
1437/// preserving its value (by extending by up to one bit as needed).
1438static void negateAsSigned(APSInt &Int) {
1439 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1440 Int = Int.extend(Int.getBitWidth() + 1);
1441 Int.setIsSigned(true);
1442 }
1443 Int = -Int;
1444}
1445
Richard Smith84401042013-06-03 05:03:02 +00001446/// Produce a string describing the given constexpr call.
1447static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1448 unsigned ArgIndex = 0;
1449 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1450 !isa<CXXConstructorDecl>(Frame->Callee) &&
1451 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1452
1453 if (!IsMemberCall)
1454 Out << *Frame->Callee << '(';
1455
1456 if (Frame->This && IsMemberCall) {
1457 APValue Val;
1458 Frame->This->moveInto(Val);
1459 Val.printPretty(Out, Frame->Info.Ctx,
1460 Frame->This->Designator.MostDerivedType);
1461 // FIXME: Add parens around Val if needed.
1462 Out << "->" << *Frame->Callee << '(';
1463 IsMemberCall = false;
1464 }
1465
1466 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1467 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1468 if (ArgIndex > (unsigned)IsMemberCall)
1469 Out << ", ";
1470
1471 const ParmVarDecl *Param = *I;
1472 const APValue &Arg = Frame->Arguments[ArgIndex];
1473 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1474
1475 if (ArgIndex == 0 && IsMemberCall)
1476 Out << "->" << *Frame->Callee << '(';
1477 }
1478
1479 Out << ')';
1480}
1481
Richard Smithd9f663b2013-04-22 15:31:51 +00001482/// Evaluate an expression to see if it had side-effects, and discard its
1483/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001484/// \return \c true if the caller should keep evaluating.
1485static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001486 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001487 if (!Evaluate(Scratch, Info, E))
1488 // We don't need the value, but we might have skipped a side effect here.
1489 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001490 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001491}
1492
Richard Smithd62306a2011-11-10 06:34:14 +00001493/// Should this call expression be treated as a string literal?
1494static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001495 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001496 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1497 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1498}
1499
Richard Smithce40ad62011-11-12 22:28:03 +00001500static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001501 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1502 // constant expression of pointer type that evaluates to...
1503
1504 // ... a null pointer value, or a prvalue core constant expression of type
1505 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001506 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001507
Richard Smithce40ad62011-11-12 22:28:03 +00001508 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1509 // ... the address of an object with static storage duration,
1510 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1511 return VD->hasGlobalStorage();
1512 // ... the address of a function,
1513 return isa<FunctionDecl>(D);
1514 }
1515
1516 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001517 switch (E->getStmtClass()) {
1518 default:
1519 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001520 case Expr::CompoundLiteralExprClass: {
1521 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1522 return CLE->isFileScope() && CLE->isLValue();
1523 }
Richard Smithe6c01442013-06-05 00:46:14 +00001524 case Expr::MaterializeTemporaryExprClass:
1525 // A materialized temporary might have been lifetime-extended to static
1526 // storage duration.
1527 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001528 // A string literal has static storage duration.
1529 case Expr::StringLiteralClass:
1530 case Expr::PredefinedExprClass:
1531 case Expr::ObjCStringLiteralClass:
1532 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001533 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001534 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001535 return true;
1536 case Expr::CallExprClass:
1537 return IsStringLiteralCall(cast<CallExpr>(E));
1538 // For GCC compatibility, &&label has static storage duration.
1539 case Expr::AddrLabelExprClass:
1540 return true;
1541 // A Block literal expression may be used as the initialization value for
1542 // Block variables at global or local static scope.
1543 case Expr::BlockExprClass:
1544 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001545 case Expr::ImplicitValueInitExprClass:
1546 // FIXME:
1547 // We can never form an lvalue with an implicit value initialization as its
1548 // base through expression evaluation, so these only appear in one case: the
1549 // implicit variable declaration we invent when checking whether a constexpr
1550 // constructor can produce a constant expression. We must assume that such
1551 // an expression might be a global lvalue.
1552 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001553 }
John McCall95007602010-05-10 23:27:23 +00001554}
1555
Richard Smithb228a862012-02-15 02:18:13 +00001556static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1557 assert(Base && "no location for a null lvalue");
1558 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1559 if (VD)
1560 Info.Note(VD->getLocation(), diag::note_declared_at);
1561 else
Ted Kremenek28831752012-08-23 20:46:57 +00001562 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001563 diag::note_constexpr_temporary_here);
1564}
1565
Richard Smith80815602011-11-07 05:07:52 +00001566/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001567/// value for an address or reference constant expression. Return true if we
1568/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001569static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1570 QualType Type, const LValue &LVal) {
1571 bool IsReferenceType = Type->isReferenceType();
1572
Richard Smith357362d2011-12-13 06:39:58 +00001573 APValue::LValueBase Base = LVal.getLValueBase();
1574 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1575
Richard Smith0dea49e2012-02-18 04:58:18 +00001576 // Check that the object is a global. Note that the fake 'this' object we
1577 // manufacture when checking potential constant expressions is conservatively
1578 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001579 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001580 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001581 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001582 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001583 << IsReferenceType << !Designator.Entries.empty()
1584 << !!VD << VD;
1585 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001586 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001587 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001588 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001589 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001590 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001591 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001592 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001593 LVal.getLValueCallIndex() == 0) &&
1594 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001595
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001596 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1597 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001598 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001599 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001600 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001601
Hans Wennborg82dd8772014-06-25 22:19:48 +00001602 // A dllimport variable never acts like a constant.
1603 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001604 return false;
1605 }
1606 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1607 // __declspec(dllimport) must be handled very carefully:
1608 // We must never initialize an expression with the thunk in C++.
1609 // Doing otherwise would allow the same id-expression to yield
1610 // different addresses for the same function in different translation
1611 // units. However, this means that we must dynamically initialize the
1612 // expression with the contents of the import address table at runtime.
1613 //
1614 // The C language has no notion of ODR; furthermore, it has no notion of
1615 // dynamic initialization. This means that we are permitted to
1616 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001617 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001618 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001619 }
1620 }
1621
Richard Smitha8105bc2012-01-06 16:39:00 +00001622 // Allow address constant expressions to be past-the-end pointers. This is
1623 // an extension: the standard requires them to point to an object.
1624 if (!IsReferenceType)
1625 return true;
1626
1627 // A reference constant expression must refer to an object.
1628 if (!Base) {
1629 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001630 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001631 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001632 }
1633
Richard Smith357362d2011-12-13 06:39:58 +00001634 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001635 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001636 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001637 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001638 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001639 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001640 }
1641
Richard Smith80815602011-11-07 05:07:52 +00001642 return true;
1643}
1644
Richard Smithfddd3842011-12-30 21:15:51 +00001645/// Check that this core constant expression is of literal type, and if not,
1646/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001647static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001648 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001649 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001650 return true;
1651
Richard Smith7525ff62013-05-09 07:14:00 +00001652 // C++1y: A constant initializer for an object o [...] may also invoke
1653 // constexpr constructors for o and its subobjects even if those objects
1654 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001655 //
1656 // C++11 missed this detail for aggregates, so classes like this:
1657 // struct foo_t { union { int i; volatile int j; } u; };
1658 // are not (obviously) initializable like so:
1659 // __attribute__((__require_constant_initialization__))
1660 // static const foo_t x = {{0}};
1661 // because "i" is a subobject with non-literal initialization (due to the
1662 // volatile member of the union). See:
1663 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1664 // Therefore, we use the C++1y behavior.
1665 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001666 return true;
1667
Richard Smithfddd3842011-12-30 21:15:51 +00001668 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001669 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001670 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001671 << E->getType();
1672 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001673 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001674 return false;
1675}
1676
Richard Smith0b0a0b62011-10-29 20:57:55 +00001677/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001678/// constant expression. If not, report an appropriate diagnostic. Does not
1679/// check that the expression is of literal type.
1680static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1681 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001682 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001683 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001684 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001685 return false;
1686 }
1687
Richard Smith77be48a2014-07-31 06:31:19 +00001688 // We allow _Atomic(T) to be initialized from anything that T can be
1689 // initialized from.
1690 if (const AtomicType *AT = Type->getAs<AtomicType>())
1691 Type = AT->getValueType();
1692
Richard Smithb228a862012-02-15 02:18:13 +00001693 // Core issue 1454: For a literal constant expression of array or class type,
1694 // each subobject of its value shall have been initialized by a constant
1695 // expression.
1696 if (Value.isArray()) {
1697 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1698 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1699 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1700 Value.getArrayInitializedElt(I)))
1701 return false;
1702 }
1703 if (!Value.hasArrayFiller())
1704 return true;
1705 return CheckConstantExpression(Info, DiagLoc, EltTy,
1706 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001707 }
Richard Smithb228a862012-02-15 02:18:13 +00001708 if (Value.isUnion() && Value.getUnionField()) {
1709 return CheckConstantExpression(Info, DiagLoc,
1710 Value.getUnionField()->getType(),
1711 Value.getUnionValue());
1712 }
1713 if (Value.isStruct()) {
1714 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1715 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1716 unsigned BaseIndex = 0;
1717 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1718 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1719 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1720 Value.getStructBase(BaseIndex)))
1721 return false;
1722 }
1723 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001724 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001725 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1726 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001727 return false;
1728 }
1729 }
1730
1731 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001732 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001733 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001734 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1735 }
1736
1737 // Everything else is fine.
1738 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001739}
1740
Benjamin Kramer8407df72015-03-09 16:47:52 +00001741static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001742 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001743}
1744
1745static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001746 if (Value.CallIndex)
1747 return false;
1748 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1749 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001750}
1751
Richard Smithcecf1842011-11-01 21:06:14 +00001752static bool IsWeakLValue(const LValue &Value) {
1753 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001754 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001755}
1756
David Majnemerb5116032014-12-09 23:32:34 +00001757static bool isZeroSized(const LValue &Value) {
1758 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001759 if (Decl && isa<VarDecl>(Decl)) {
1760 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001761 if (Ty->isArrayType())
1762 return Ty->isIncompleteType() ||
1763 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001764 }
1765 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001766}
1767
Richard Smith2e312c82012-03-03 22:46:17 +00001768static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001769 // A null base expression indicates a null pointer. These are always
1770 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001771 if (!Value.getLValueBase()) {
1772 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001773 return true;
1774 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001775
Richard Smith027bf112011-11-17 22:56:20 +00001776 // We have a non-null base. These are generally known to be true, but if it's
1777 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001778 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001779 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001780 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001781}
1782
Richard Smith2e312c82012-03-03 22:46:17 +00001783static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001784 switch (Val.getKind()) {
1785 case APValue::Uninitialized:
1786 return false;
1787 case APValue::Int:
1788 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001789 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001790 case APValue::Float:
1791 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001792 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001793 case APValue::ComplexInt:
1794 Result = Val.getComplexIntReal().getBoolValue() ||
1795 Val.getComplexIntImag().getBoolValue();
1796 return true;
1797 case APValue::ComplexFloat:
1798 Result = !Val.getComplexFloatReal().isZero() ||
1799 !Val.getComplexFloatImag().isZero();
1800 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001801 case APValue::LValue:
1802 return EvalPointerValueAsBool(Val, Result);
1803 case APValue::MemberPointer:
1804 Result = Val.getMemberPointerDecl();
1805 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001806 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001807 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001808 case APValue::Struct:
1809 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001810 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001811 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001812 }
1813
Richard Smith11562c52011-10-28 17:51:58 +00001814 llvm_unreachable("unknown APValue kind");
1815}
1816
1817static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1818 EvalInfo &Info) {
1819 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001820 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001821 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001822 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001823 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001824}
1825
Richard Smith357362d2011-12-13 06:39:58 +00001826template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001827static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001828 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001829 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001830 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001831 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001832}
1833
1834static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1835 QualType SrcType, const APFloat &Value,
1836 QualType DestType, APSInt &Result) {
1837 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001838 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001839 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001840
Richard Smith357362d2011-12-13 06:39:58 +00001841 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001842 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001843 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1844 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001845 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001846 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001847}
1848
Richard Smith357362d2011-12-13 06:39:58 +00001849static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1850 QualType SrcType, QualType DestType,
1851 APFloat &Result) {
1852 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001853 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001854 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1855 APFloat::rmNearestTiesToEven, &ignored)
1856 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001857 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001858 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001859}
1860
Richard Smith911e1422012-01-30 22:27:01 +00001861static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1862 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001863 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001864 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001865 APSInt Result = Value;
1866 // Figure out if this is a truncate, extend or noop cast.
1867 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001868 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001869 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001870 return Result;
1871}
1872
Richard Smith357362d2011-12-13 06:39:58 +00001873static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1874 QualType SrcType, const APSInt &Value,
1875 QualType DestType, APFloat &Result) {
1876 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1877 if (Result.convertFromAPInt(Value, Value.isSigned(),
1878 APFloat::rmNearestTiesToEven)
1879 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001880 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001881 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001882}
1883
Richard Smith49ca8aa2013-08-06 07:09:20 +00001884static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1885 APValue &Value, const FieldDecl *FD) {
1886 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1887
1888 if (!Value.isInt()) {
1889 // Trying to store a pointer-cast-to-integer into a bitfield.
1890 // FIXME: In this case, we should provide the diagnostic for casting
1891 // a pointer to an integer.
1892 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001893 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001894 return false;
1895 }
1896
1897 APSInt &Int = Value.getInt();
1898 unsigned OldBitWidth = Int.getBitWidth();
1899 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1900 if (NewBitWidth < OldBitWidth)
1901 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1902 return true;
1903}
1904
Eli Friedman803acb32011-12-22 03:51:45 +00001905static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1906 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001907 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001908 if (!Evaluate(SVal, Info, E))
1909 return false;
1910 if (SVal.isInt()) {
1911 Res = SVal.getInt();
1912 return true;
1913 }
1914 if (SVal.isFloat()) {
1915 Res = SVal.getFloat().bitcastToAPInt();
1916 return true;
1917 }
1918 if (SVal.isVector()) {
1919 QualType VecTy = E->getType();
1920 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1921 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1922 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1923 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1924 Res = llvm::APInt::getNullValue(VecSize);
1925 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1926 APValue &Elt = SVal.getVectorElt(i);
1927 llvm::APInt EltAsInt;
1928 if (Elt.isInt()) {
1929 EltAsInt = Elt.getInt();
1930 } else if (Elt.isFloat()) {
1931 EltAsInt = Elt.getFloat().bitcastToAPInt();
1932 } else {
1933 // Don't try to handle vectors of anything other than int or float
1934 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001935 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001936 return false;
1937 }
1938 unsigned BaseEltSize = EltAsInt.getBitWidth();
1939 if (BigEndian)
1940 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1941 else
1942 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1943 }
1944 return true;
1945 }
1946 // Give up if the input isn't an int, float, or vector. For example, we
1947 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001948 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001949 return false;
1950}
1951
Richard Smith43e77732013-05-07 04:50:00 +00001952/// Perform the given integer operation, which is known to need at most BitWidth
1953/// bits, and check for overflow in the original type (if that type was not an
1954/// unsigned type).
1955template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001956static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1957 const APSInt &LHS, const APSInt &RHS,
1958 unsigned BitWidth, Operation Op,
1959 APSInt &Result) {
1960 if (LHS.isUnsigned()) {
1961 Result = Op(LHS, RHS);
1962 return true;
1963 }
Richard Smith43e77732013-05-07 04:50:00 +00001964
1965 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001966 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001967 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001968 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001969 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001970 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001971 << Result.toString(10) << E->getType();
1972 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001973 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001974 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001975 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001976}
1977
1978/// Perform the given binary integer operation.
1979static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1980 BinaryOperatorKind Opcode, APSInt RHS,
1981 APSInt &Result) {
1982 switch (Opcode) {
1983 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001984 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00001985 return false;
1986 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001987 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1988 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001989 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00001990 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1991 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001992 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00001993 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1994 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001995 case BO_And: Result = LHS & RHS; return true;
1996 case BO_Xor: Result = LHS ^ RHS; return true;
1997 case BO_Or: Result = LHS | RHS; return true;
1998 case BO_Div:
1999 case BO_Rem:
2000 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002001 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002002 return false;
2003 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002004 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2005 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2006 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002007 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2008 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002009 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2010 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002011 return true;
2012 case BO_Shl: {
2013 if (Info.getLangOpts().OpenCL)
2014 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2015 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2016 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2017 RHS.isUnsigned());
2018 else if (RHS.isSigned() && RHS.isNegative()) {
2019 // During constant-folding, a negative shift is an opposite shift. Such
2020 // a shift is not a constant expression.
2021 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2022 RHS = -RHS;
2023 goto shift_right;
2024 }
2025 shift_left:
2026 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2027 // the shifted type.
2028 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2029 if (SA != RHS) {
2030 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2031 << RHS << E->getType() << LHS.getBitWidth();
2032 } else if (LHS.isSigned()) {
2033 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2034 // operand, and must not overflow the corresponding unsigned type.
2035 if (LHS.isNegative())
2036 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2037 else if (LHS.countLeadingZeros() < SA)
2038 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2039 }
2040 Result = LHS << SA;
2041 return true;
2042 }
2043 case BO_Shr: {
2044 if (Info.getLangOpts().OpenCL)
2045 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2046 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2047 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2048 RHS.isUnsigned());
2049 else if (RHS.isSigned() && RHS.isNegative()) {
2050 // During constant-folding, a negative shift is an opposite shift. Such a
2051 // shift is not a constant expression.
2052 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2053 RHS = -RHS;
2054 goto shift_left;
2055 }
2056 shift_right:
2057 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2058 // shifted type.
2059 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2060 if (SA != RHS)
2061 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2062 << RHS << E->getType() << LHS.getBitWidth();
2063 Result = LHS >> SA;
2064 return true;
2065 }
2066
2067 case BO_LT: Result = LHS < RHS; return true;
2068 case BO_GT: Result = LHS > RHS; return true;
2069 case BO_LE: Result = LHS <= RHS; return true;
2070 case BO_GE: Result = LHS >= RHS; return true;
2071 case BO_EQ: Result = LHS == RHS; return true;
2072 case BO_NE: Result = LHS != RHS; return true;
2073 }
2074}
2075
Richard Smith861b5b52013-05-07 23:34:45 +00002076/// Perform the given binary floating-point operation, in-place, on LHS.
2077static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2078 APFloat &LHS, BinaryOperatorKind Opcode,
2079 const APFloat &RHS) {
2080 switch (Opcode) {
2081 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002082 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002083 return false;
2084 case BO_Mul:
2085 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2086 break;
2087 case BO_Add:
2088 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2089 break;
2090 case BO_Sub:
2091 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2092 break;
2093 case BO_Div:
2094 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2095 break;
2096 }
2097
Richard Smith0c6124b2015-12-03 01:36:22 +00002098 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002099 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002100 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002101 }
Richard Smith861b5b52013-05-07 23:34:45 +00002102 return true;
2103}
2104
Richard Smitha8105bc2012-01-06 16:39:00 +00002105/// Cast an lvalue referring to a base subobject to a derived class, by
2106/// truncating the lvalue's path to the given length.
2107static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2108 const RecordDecl *TruncatedType,
2109 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002110 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002111
2112 // Check we actually point to a derived class object.
2113 if (TruncatedElements == D.Entries.size())
2114 return true;
2115 assert(TruncatedElements >= D.MostDerivedPathLength &&
2116 "not casting to a derived class");
2117 if (!Result.checkSubobject(Info, E, CSK_Derived))
2118 return false;
2119
2120 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002121 const RecordDecl *RD = TruncatedType;
2122 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002123 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002124 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2125 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002126 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002127 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002128 else
Richard Smithd62306a2011-11-10 06:34:14 +00002129 Result.Offset -= Layout.getBaseClassOffset(Base);
2130 RD = Base;
2131 }
Richard Smith027bf112011-11-17 22:56:20 +00002132 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002133 return true;
2134}
2135
John McCalld7bca762012-05-01 00:38:49 +00002136static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002137 const CXXRecordDecl *Derived,
2138 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002139 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002140 if (!RL) {
2141 if (Derived->isInvalidDecl()) return false;
2142 RL = &Info.Ctx.getASTRecordLayout(Derived);
2143 }
2144
Richard Smithd62306a2011-11-10 06:34:14 +00002145 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002146 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002147 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002148}
2149
Richard Smitha8105bc2012-01-06 16:39:00 +00002150static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002151 const CXXRecordDecl *DerivedDecl,
2152 const CXXBaseSpecifier *Base) {
2153 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2154
John McCalld7bca762012-05-01 00:38:49 +00002155 if (!Base->isVirtual())
2156 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002157
Richard Smitha8105bc2012-01-06 16:39:00 +00002158 SubobjectDesignator &D = Obj.Designator;
2159 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002160 return false;
2161
Richard Smitha8105bc2012-01-06 16:39:00 +00002162 // Extract most-derived object and corresponding type.
2163 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2164 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2165 return false;
2166
2167 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002168 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002169 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2170 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002171 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002172 return true;
2173}
2174
Richard Smith84401042013-06-03 05:03:02 +00002175static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2176 QualType Type, LValue &Result) {
2177 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2178 PathE = E->path_end();
2179 PathI != PathE; ++PathI) {
2180 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2181 *PathI))
2182 return false;
2183 Type = (*PathI)->getType();
2184 }
2185 return true;
2186}
2187
Richard Smithd62306a2011-11-10 06:34:14 +00002188/// Update LVal to refer to the given field, which must be a member of the type
2189/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002190static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002191 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002192 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002193 if (!RL) {
2194 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002195 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002196 }
Richard Smithd62306a2011-11-10 06:34:14 +00002197
2198 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002199 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002200 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002201 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002202}
2203
Richard Smith1b78b3d2012-01-25 22:15:11 +00002204/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002205static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002206 LValue &LVal,
2207 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002208 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002209 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002210 return false;
2211 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002212}
2213
Richard Smithd62306a2011-11-10 06:34:14 +00002214/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002215static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2216 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002217 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2218 // extension.
2219 if (Type->isVoidType() || Type->isFunctionType()) {
2220 Size = CharUnits::One();
2221 return true;
2222 }
2223
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002224 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002225 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002226 return false;
2227 }
2228
Richard Smithd62306a2011-11-10 06:34:14 +00002229 if (!Type->isConstantSizeType()) {
2230 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002231 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002232 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002233 return false;
2234 }
2235
2236 Size = Info.Ctx.getTypeSizeInChars(Type);
2237 return true;
2238}
2239
2240/// Update a pointer value to model pointer arithmetic.
2241/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002242/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002243/// \param LVal - The pointer value to be updated.
2244/// \param EltTy - The pointee type represented by LVal.
2245/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002246static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2247 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002248 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002249 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002250 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002251 return false;
2252
Yaxun Liu402804b2016-12-15 08:09:08 +00002253 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002254 return true;
2255}
2256
Richard Smithd6cc1982017-01-31 02:23:02 +00002257static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2258 LValue &LVal, QualType EltTy,
2259 int64_t Adjustment) {
2260 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2261 APSInt::get(Adjustment));
2262}
2263
Richard Smith66c96992012-02-18 22:04:06 +00002264/// Update an lvalue to refer to a component of a complex number.
2265/// \param Info - Information about the ongoing evaluation.
2266/// \param LVal - The lvalue to be updated.
2267/// \param EltTy - The complex number's component type.
2268/// \param Imag - False for the real component, true for the imaginary.
2269static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2270 LValue &LVal, QualType EltTy,
2271 bool Imag) {
2272 if (Imag) {
2273 CharUnits SizeOfComponent;
2274 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2275 return false;
2276 LVal.Offset += SizeOfComponent;
2277 }
2278 LVal.addComplex(Info, E, EltTy, Imag);
2279 return true;
2280}
2281
Richard Smith27908702011-10-24 17:54:18 +00002282/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002283///
2284/// \param Info Information about the ongoing evaluation.
2285/// \param E An expression to be used when printing diagnostics.
2286/// \param VD The variable whose initializer should be obtained.
2287/// \param Frame The frame in which the variable was created. Must be null
2288/// if this variable is not local to the evaluation.
2289/// \param Result Filled in with a pointer to the value of the variable.
2290static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2291 const VarDecl *VD, CallStackFrame *Frame,
2292 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002293 // If this is a parameter to an active constexpr function call, perform
2294 // argument substitution.
2295 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002296 // Assume arguments of a potential constant expression are unknown
2297 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002298 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002299 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002300 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002301 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002302 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002303 }
Richard Smith3229b742013-05-05 21:17:10 +00002304 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002305 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002306 }
Richard Smith27908702011-10-24 17:54:18 +00002307
Richard Smithd9f663b2013-04-22 15:31:51 +00002308 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002309 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002310 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002311 if (!Result) {
2312 // Assume variables referenced within a lambda's call operator that were
2313 // not declared within the call operator are captures and during checking
2314 // of a potential constant expression, assume they are unknown constant
2315 // expressions.
2316 assert(isLambdaCallOperator(Frame->Callee) &&
2317 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2318 "missing value for local variable");
2319 if (Info.checkingPotentialConstantExpression())
2320 return false;
2321 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002322 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002323 diag::note_unimplemented_constexpr_lambda_feature_ast)
2324 << "captures not currently allowed";
2325 return false;
2326 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002327 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002328 }
2329
Richard Smithd0b4dd62011-12-19 06:19:21 +00002330 // Dig out the initializer, and use the declaration which it's attached to.
2331 const Expr *Init = VD->getAnyInitializer(VD);
2332 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002333 // If we're checking a potential constant expression, the variable could be
2334 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002335 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002336 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002337 return false;
2338 }
2339
Richard Smithd62306a2011-11-10 06:34:14 +00002340 // If we're currently evaluating the initializer of this declaration, use that
2341 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002342 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002343 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002344 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002345 }
2346
Richard Smithcecf1842011-11-01 21:06:14 +00002347 // Never evaluate the initializer of a weak variable. We can't be sure that
2348 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002349 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002350 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002351 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002352 }
Richard Smithcecf1842011-11-01 21:06:14 +00002353
Richard Smithd0b4dd62011-12-19 06:19:21 +00002354 // Check that we can fold the initializer. In C++, we will have already done
2355 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002356 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002357 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002358 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002359 Notes.size() + 1) << VD;
2360 Info.Note(VD->getLocation(), diag::note_declared_at);
2361 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002362 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002363 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002364 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002365 Notes.size() + 1) << VD;
2366 Info.Note(VD->getLocation(), diag::note_declared_at);
2367 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002368 }
Richard Smith27908702011-10-24 17:54:18 +00002369
Richard Smith3229b742013-05-05 21:17:10 +00002370 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002371 return true;
Richard Smith27908702011-10-24 17:54:18 +00002372}
2373
Richard Smith11562c52011-10-28 17:51:58 +00002374static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002375 Qualifiers Quals = T.getQualifiers();
2376 return Quals.hasConst() && !Quals.hasVolatile();
2377}
2378
Richard Smithe97cbd72011-11-11 04:05:33 +00002379/// Get the base index of the given base class within an APValue representing
2380/// the given derived class.
2381static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2382 const CXXRecordDecl *Base) {
2383 Base = Base->getCanonicalDecl();
2384 unsigned Index = 0;
2385 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2386 E = Derived->bases_end(); I != E; ++I, ++Index) {
2387 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2388 return Index;
2389 }
2390
2391 llvm_unreachable("base class missing from derived class's bases list");
2392}
2393
Richard Smith3da88fa2013-04-26 14:36:30 +00002394/// Extract the value of a character from a string literal.
2395static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2396 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002397 // FIXME: Support MakeStringConstant
2398 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2399 std::string Str;
2400 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2401 assert(Index <= Str.size() && "Index too large");
2402 return APSInt::getUnsigned(Str.c_str()[Index]);
2403 }
2404
Alexey Bataevec474782014-10-09 08:45:04 +00002405 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2406 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002407 const StringLiteral *S = cast<StringLiteral>(Lit);
2408 const ConstantArrayType *CAT =
2409 Info.Ctx.getAsConstantArrayType(S->getType());
2410 assert(CAT && "string literal isn't an array");
2411 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002412 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002413
2414 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002415 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002416 if (Index < S->getLength())
2417 Value = S->getCodeUnit(Index);
2418 return Value;
2419}
2420
Richard Smith3da88fa2013-04-26 14:36:30 +00002421// Expand a string literal into an array of characters.
2422static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2423 APValue &Result) {
2424 const StringLiteral *S = cast<StringLiteral>(Lit);
2425 const ConstantArrayType *CAT =
2426 Info.Ctx.getAsConstantArrayType(S->getType());
2427 assert(CAT && "string literal isn't an array");
2428 QualType CharType = CAT->getElementType();
2429 assert(CharType->isIntegerType() && "unexpected character type");
2430
2431 unsigned Elts = CAT->getSize().getZExtValue();
2432 Result = APValue(APValue::UninitArray(),
2433 std::min(S->getLength(), Elts), Elts);
2434 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2435 CharType->isUnsignedIntegerType());
2436 if (Result.hasArrayFiller())
2437 Result.getArrayFiller() = APValue(Value);
2438 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2439 Value = S->getCodeUnit(I);
2440 Result.getArrayInitializedElt(I) = APValue(Value);
2441 }
2442}
2443
2444// Expand an array so that it has more than Index filled elements.
2445static void expandArray(APValue &Array, unsigned Index) {
2446 unsigned Size = Array.getArraySize();
2447 assert(Index < Size);
2448
2449 // Always at least double the number of elements for which we store a value.
2450 unsigned OldElts = Array.getArrayInitializedElts();
2451 unsigned NewElts = std::max(Index+1, OldElts * 2);
2452 NewElts = std::min(Size, std::max(NewElts, 8u));
2453
2454 // Copy the data across.
2455 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2456 for (unsigned I = 0; I != OldElts; ++I)
2457 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2458 for (unsigned I = OldElts; I != NewElts; ++I)
2459 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2460 if (NewValue.hasArrayFiller())
2461 NewValue.getArrayFiller() = Array.getArrayFiller();
2462 Array.swap(NewValue);
2463}
2464
Richard Smithb01fe402014-09-16 01:24:02 +00002465/// Determine whether a type would actually be read by an lvalue-to-rvalue
2466/// conversion. If it's of class type, we may assume that the copy operation
2467/// is trivial. Note that this is never true for a union type with fields
2468/// (because the copy always "reads" the active member) and always true for
2469/// a non-class type.
2470static bool isReadByLvalueToRvalueConversion(QualType T) {
2471 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2472 if (!RD || (RD->isUnion() && !RD->field_empty()))
2473 return true;
2474 if (RD->isEmpty())
2475 return false;
2476
2477 for (auto *Field : RD->fields())
2478 if (isReadByLvalueToRvalueConversion(Field->getType()))
2479 return true;
2480
2481 for (auto &BaseSpec : RD->bases())
2482 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2483 return true;
2484
2485 return false;
2486}
2487
2488/// Diagnose an attempt to read from any unreadable field within the specified
2489/// type, which might be a class type.
2490static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2491 QualType T) {
2492 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2493 if (!RD)
2494 return false;
2495
2496 if (!RD->hasMutableFields())
2497 return false;
2498
2499 for (auto *Field : RD->fields()) {
2500 // If we're actually going to read this field in some way, then it can't
2501 // be mutable. If we're in a union, then assigning to a mutable field
2502 // (even an empty one) can change the active member, so that's not OK.
2503 // FIXME: Add core issue number for the union case.
2504 if (Field->isMutable() &&
2505 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002506 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002507 Info.Note(Field->getLocation(), diag::note_declared_at);
2508 return true;
2509 }
2510
2511 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2512 return true;
2513 }
2514
2515 for (auto &BaseSpec : RD->bases())
2516 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2517 return true;
2518
2519 // All mutable fields were empty, and thus not actually read.
2520 return false;
2521}
2522
Richard Smith861b5b52013-05-07 23:34:45 +00002523/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002524enum AccessKinds {
2525 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002526 AK_Assign,
2527 AK_Increment,
2528 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002529};
2530
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002531namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002532/// A handle to a complete object (an object that is not a subobject of
2533/// another object).
2534struct CompleteObject {
2535 /// The value of the complete object.
2536 APValue *Value;
2537 /// The type of the complete object.
2538 QualType Type;
2539
Craig Topper36250ad2014-05-12 05:36:57 +00002540 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002541 CompleteObject(APValue *Value, QualType Type)
2542 : Value(Value), Type(Type) {
2543 assert(Value && "missing value for complete object");
2544 }
2545
Aaron Ballman67347662015-02-15 22:00:28 +00002546 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002547};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002548} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002549
Richard Smith3da88fa2013-04-26 14:36:30 +00002550/// Find the designated sub-object of an rvalue.
2551template<typename SubobjectHandler>
2552typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002553findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002554 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002555 if (Sub.Invalid)
2556 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002557 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002558 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002559 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002560 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002561 << handler.AccessKind;
2562 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002563 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002564 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002565 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002566
Richard Smith3229b742013-05-05 21:17:10 +00002567 APValue *O = Obj.Value;
2568 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002569 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002570
Richard Smithd62306a2011-11-10 06:34:14 +00002571 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002572 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2573 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002574 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002575 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002576 return handler.failed();
2577 }
2578
Richard Smith49ca8aa2013-08-06 07:09:20 +00002579 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002580 // If we are reading an object of class type, there may still be more
2581 // things we need to check: if there are any mutable subobjects, we
2582 // cannot perform this read. (This only happens when performing a trivial
2583 // copy or assignment.)
2584 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2585 diagnoseUnreadableFields(Info, E, ObjType))
2586 return handler.failed();
2587
Richard Smith49ca8aa2013-08-06 07:09:20 +00002588 if (!handler.found(*O, ObjType))
2589 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002590
Richard Smith49ca8aa2013-08-06 07:09:20 +00002591 // If we modified a bit-field, truncate it to the right width.
2592 if (handler.AccessKind != AK_Read &&
2593 LastField && LastField->isBitField() &&
2594 !truncateBitfieldValue(Info, E, *O, LastField))
2595 return false;
2596
2597 return true;
2598 }
2599
Craig Topper36250ad2014-05-12 05:36:57 +00002600 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002601 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002602 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002603 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002604 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002605 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002606 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002607 // Note, it should not be possible to form a pointer with a valid
2608 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002609 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002610 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002611 << handler.AccessKind;
2612 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002613 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002614 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002615 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002616
2617 ObjType = CAT->getElementType();
2618
Richard Smith14a94132012-02-17 03:35:37 +00002619 // An array object is represented as either an Array APValue or as an
2620 // LValue which refers to a string literal.
2621 if (O->isLValue()) {
2622 assert(I == N - 1 && "extracting subobject of character?");
2623 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002624 if (handler.AccessKind != AK_Read)
2625 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2626 *O);
2627 else
2628 return handler.foundString(*O, ObjType, Index);
2629 }
2630
2631 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002632 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002633 else if (handler.AccessKind != AK_Read) {
2634 expandArray(*O, Index);
2635 O = &O->getArrayInitializedElt(Index);
2636 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002637 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002638 } else if (ObjType->isAnyComplexType()) {
2639 // Next subobject is a complex number.
2640 uint64_t Index = Sub.Entries[I].ArrayIndex;
2641 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002642 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002643 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002644 << handler.AccessKind;
2645 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002646 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002647 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002648 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002649
2650 bool WasConstQualified = ObjType.isConstQualified();
2651 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2652 if (WasConstQualified)
2653 ObjType.addConst();
2654
Richard Smith66c96992012-02-18 22:04:06 +00002655 assert(I == N - 1 && "extracting subobject of scalar?");
2656 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002657 return handler.found(Index ? O->getComplexIntImag()
2658 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002659 } else {
2660 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002661 return handler.found(Index ? O->getComplexFloatImag()
2662 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002663 }
Richard Smithd62306a2011-11-10 06:34:14 +00002664 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002665 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002666 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002667 << Field;
2668 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002669 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002670 }
2671
Richard Smithd62306a2011-11-10 06:34:14 +00002672 // Next subobject is a class, struct or union field.
2673 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2674 if (RD->isUnion()) {
2675 const FieldDecl *UnionField = O->getUnionField();
2676 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002677 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002678 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002679 << handler.AccessKind << Field << !UnionField << UnionField;
2680 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002681 }
Richard Smithd62306a2011-11-10 06:34:14 +00002682 O = &O->getUnionValue();
2683 } else
2684 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002685
2686 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002687 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002688 if (WasConstQualified && !Field->isMutable())
2689 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002690
2691 if (ObjType.isVolatileQualified()) {
2692 if (Info.getLangOpts().CPlusPlus) {
2693 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002694 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002695 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002696 Info.Note(Field->getLocation(), diag::note_declared_at);
2697 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002698 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002699 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002700 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002701 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002702
2703 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002704 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002705 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002706 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2707 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2708 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002709
2710 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002711 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002712 if (WasConstQualified)
2713 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002714 }
2715 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002716}
2717
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002718namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002719struct ExtractSubobjectHandler {
2720 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002721 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002722
2723 static const AccessKinds AccessKind = AK_Read;
2724
2725 typedef bool result_type;
2726 bool failed() { return false; }
2727 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002728 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002729 return true;
2730 }
2731 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002732 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002733 return true;
2734 }
2735 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002736 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002737 return true;
2738 }
2739 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002740 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002741 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2742 return true;
2743 }
2744};
Richard Smith3229b742013-05-05 21:17:10 +00002745} // end anonymous namespace
2746
Richard Smith3da88fa2013-04-26 14:36:30 +00002747const AccessKinds ExtractSubobjectHandler::AccessKind;
2748
2749/// Extract the designated sub-object of an rvalue.
2750static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002751 const CompleteObject &Obj,
2752 const SubobjectDesignator &Sub,
2753 APValue &Result) {
2754 ExtractSubobjectHandler Handler = { Info, Result };
2755 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002756}
2757
Richard Smith3229b742013-05-05 21:17:10 +00002758namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002759struct ModifySubobjectHandler {
2760 EvalInfo &Info;
2761 APValue &NewVal;
2762 const Expr *E;
2763
2764 typedef bool result_type;
2765 static const AccessKinds AccessKind = AK_Assign;
2766
2767 bool checkConst(QualType QT) {
2768 // Assigning to a const object has undefined behavior.
2769 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002770 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002771 return false;
2772 }
2773 return true;
2774 }
2775
2776 bool failed() { return false; }
2777 bool found(APValue &Subobj, QualType SubobjType) {
2778 if (!checkConst(SubobjType))
2779 return false;
2780 // We've been given ownership of NewVal, so just swap it in.
2781 Subobj.swap(NewVal);
2782 return true;
2783 }
2784 bool found(APSInt &Value, QualType SubobjType) {
2785 if (!checkConst(SubobjType))
2786 return false;
2787 if (!NewVal.isInt()) {
2788 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002789 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002790 return false;
2791 }
2792 Value = NewVal.getInt();
2793 return true;
2794 }
2795 bool found(APFloat &Value, QualType SubobjType) {
2796 if (!checkConst(SubobjType))
2797 return false;
2798 Value = NewVal.getFloat();
2799 return true;
2800 }
2801 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2802 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2803 }
2804};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002805} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002806
Richard Smith3229b742013-05-05 21:17:10 +00002807const AccessKinds ModifySubobjectHandler::AccessKind;
2808
Richard Smith3da88fa2013-04-26 14:36:30 +00002809/// Update the designated sub-object of an rvalue to the given value.
2810static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002811 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002812 const SubobjectDesignator &Sub,
2813 APValue &NewVal) {
2814 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002815 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002816}
2817
Richard Smith84f6dcf2012-02-02 01:16:57 +00002818/// Find the position where two subobject designators diverge, or equivalently
2819/// the length of the common initial subsequence.
2820static unsigned FindDesignatorMismatch(QualType ObjType,
2821 const SubobjectDesignator &A,
2822 const SubobjectDesignator &B,
2823 bool &WasArrayIndex) {
2824 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2825 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002826 if (!ObjType.isNull() &&
2827 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002828 // Next subobject is an array element.
2829 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2830 WasArrayIndex = true;
2831 return I;
2832 }
Richard Smith66c96992012-02-18 22:04:06 +00002833 if (ObjType->isAnyComplexType())
2834 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2835 else
2836 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002837 } else {
2838 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2839 WasArrayIndex = false;
2840 return I;
2841 }
2842 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2843 // Next subobject is a field.
2844 ObjType = FD->getType();
2845 else
2846 // Next subobject is a base class.
2847 ObjType = QualType();
2848 }
2849 }
2850 WasArrayIndex = false;
2851 return I;
2852}
2853
2854/// Determine whether the given subobject designators refer to elements of the
2855/// same array object.
2856static bool AreElementsOfSameArray(QualType ObjType,
2857 const SubobjectDesignator &A,
2858 const SubobjectDesignator &B) {
2859 if (A.Entries.size() != B.Entries.size())
2860 return false;
2861
George Burgess IVa51c4072015-10-16 01:49:01 +00002862 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002863 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2864 // A is a subobject of the array element.
2865 return false;
2866
2867 // If A (and B) designates an array element, the last entry will be the array
2868 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2869 // of length 1' case, and the entire path must match.
2870 bool WasArrayIndex;
2871 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2872 return CommonLength >= A.Entries.size() - IsArray;
2873}
2874
Richard Smith3229b742013-05-05 21:17:10 +00002875/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002876static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2877 AccessKinds AK, const LValue &LVal,
2878 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002879 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002880 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002881 return CompleteObject();
2882 }
2883
Craig Topper36250ad2014-05-12 05:36:57 +00002884 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002885 if (LVal.CallIndex) {
2886 Frame = Info.getCallFrame(LVal.CallIndex);
2887 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002888 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002889 << AK << LVal.Base.is<const ValueDecl*>();
2890 NoteLValueLocation(Info, LVal.Base);
2891 return CompleteObject();
2892 }
Richard Smith3229b742013-05-05 21:17:10 +00002893 }
2894
2895 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2896 // is not a constant expression (even if the object is non-volatile). We also
2897 // apply this rule to C++98, in order to conform to the expected 'volatile'
2898 // semantics.
2899 if (LValType.isVolatileQualified()) {
2900 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002901 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002902 << AK << LValType;
2903 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002904 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002905 return CompleteObject();
2906 }
2907
2908 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002909 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002910 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002911
2912 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2913 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2914 // In C++11, constexpr, non-volatile variables initialized with constant
2915 // expressions are constant expressions too. Inside constexpr functions,
2916 // parameters are constant expressions even if they're non-const.
2917 // In C++1y, objects local to a constant expression (those with a Frame) are
2918 // both readable and writable inside constant expressions.
2919 // In C, such things can also be folded, although they are not ICEs.
2920 const VarDecl *VD = dyn_cast<VarDecl>(D);
2921 if (VD) {
2922 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2923 VD = VDef;
2924 }
2925 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002926 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002927 return CompleteObject();
2928 }
2929
2930 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002931 if (BaseType.isVolatileQualified()) {
2932 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002933 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002934 << AK << 1 << VD;
2935 Info.Note(VD->getLocation(), diag::note_declared_at);
2936 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002937 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002938 }
2939 return CompleteObject();
2940 }
2941
2942 // Unless we're looking at a local variable or argument in a constexpr call,
2943 // the variable we're reading must be const.
2944 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002945 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002946 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2947 // OK, we can read and modify an object if we're in the process of
2948 // evaluating its initializer, because its lifetime began in this
2949 // evaluation.
2950 } else if (AK != AK_Read) {
2951 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002952 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002953 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00002954 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002955 // OK, we can read this variable.
2956 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002957 // In OpenCL if a variable is in constant address space it is a const value.
2958 if (!(BaseType.isConstQualified() ||
2959 (Info.getLangOpts().OpenCL &&
2960 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002961 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002962 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002963 Info.Note(VD->getLocation(), diag::note_declared_at);
2964 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002965 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002966 }
2967 return CompleteObject();
2968 }
2969 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2970 // We support folding of const floating-point types, in order to make
2971 // static const data members of such types (supported as an extension)
2972 // more useful.
2973 if (Info.getLangOpts().CPlusPlus11) {
2974 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2975 Info.Note(VD->getLocation(), diag::note_declared_at);
2976 } else {
2977 Info.CCEDiag(E);
2978 }
George Burgess IVb5316982016-12-27 05:33:20 +00002979 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
2980 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
2981 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00002982 } else {
2983 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00002984 if (Info.checkingPotentialConstantExpression() &&
2985 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2986 // The definition of this variable could be constexpr. We can't
2987 // access it right now, but may be able to in future.
2988 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002989 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002990 Info.Note(VD->getLocation(), diag::note_declared_at);
2991 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002992 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002993 }
2994 return CompleteObject();
2995 }
2996 }
2997
2998 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2999 return CompleteObject();
3000 } else {
3001 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3002
3003 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003004 if (const MaterializeTemporaryExpr *MTE =
3005 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3006 assert(MTE->getStorageDuration() == SD_Static &&
3007 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003008
Richard Smithe6c01442013-06-05 00:46:14 +00003009 // Per C++1y [expr.const]p2:
3010 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3011 // - a [...] glvalue of integral or enumeration type that refers to
3012 // a non-volatile const object [...]
3013 // [...]
3014 // - a [...] glvalue of literal type that refers to a non-volatile
3015 // object whose lifetime began within the evaluation of e.
3016 //
3017 // C++11 misses the 'began within the evaluation of e' check and
3018 // instead allows all temporaries, including things like:
3019 // int &&r = 1;
3020 // int x = ++r;
3021 // constexpr int k = r;
3022 // Therefore we use the C++1y rules in C++11 too.
3023 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3024 const ValueDecl *ED = MTE->getExtendingDecl();
3025 if (!(BaseType.isConstQualified() &&
3026 BaseType->isIntegralOrEnumerationType()) &&
3027 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003028 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003029 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3030 return CompleteObject();
3031 }
3032
3033 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3034 assert(BaseVal && "got reference to unevaluated temporary");
3035 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003036 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003037 return CompleteObject();
3038 }
3039 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003040 BaseVal = Frame->getTemporary(Base);
3041 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003042 }
Richard Smith3229b742013-05-05 21:17:10 +00003043
3044 // Volatile temporary objects cannot be accessed in constant expressions.
3045 if (BaseType.isVolatileQualified()) {
3046 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003047 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003048 << AK << 0;
3049 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3050 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003051 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003052 }
3053 return CompleteObject();
3054 }
3055 }
3056
Richard Smith7525ff62013-05-09 07:14:00 +00003057 // During the construction of an object, it is not yet 'const'.
3058 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3059 // and this doesn't do quite the right thing for const subobjects of the
3060 // object under construction.
3061 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3062 BaseType = Info.Ctx.getCanonicalType(BaseType);
3063 BaseType.removeLocalConst();
3064 }
3065
Richard Smith6d4c6582013-11-05 22:18:15 +00003066 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003067 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003068 //
3069 // FIXME: Not all local state is mutable. Allow local constant subobjects
3070 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003071 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3072 Info.EvalStatus.HasSideEffects) ||
3073 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003074 return CompleteObject();
3075
3076 return CompleteObject(BaseVal, BaseType);
3077}
3078
Richard Smith243ef902013-05-05 23:31:59 +00003079/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3080/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3081/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003082///
3083/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003084/// \param Conv - The expression for which we are performing the conversion.
3085/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003086/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3087/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003088/// \param LVal - The glvalue on which we are attempting to perform this action.
3089/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003090static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003091 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003092 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003093 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003094 return false;
3095
Richard Smith3229b742013-05-05 21:17:10 +00003096 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003097 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003098 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003099 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3100 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3101 // initializer until now for such expressions. Such an expression can't be
3102 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003103 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003104 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003105 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003106 }
Richard Smith3229b742013-05-05 21:17:10 +00003107 APValue Lit;
3108 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3109 return false;
3110 CompleteObject LitObj(&Lit, Base->getType());
3111 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003112 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003113 // We represent a string literal array as an lvalue pointing at the
3114 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003115 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003116 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3117 CompleteObject StrObj(&Str, Base->getType());
3118 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003119 }
Richard Smith11562c52011-10-28 17:51:58 +00003120 }
3121
Richard Smith3229b742013-05-05 21:17:10 +00003122 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3123 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003124}
3125
3126/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003127static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003128 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003129 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003130 return false;
3131
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003132 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003133 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003134 return false;
3135 }
3136
Richard Smith3229b742013-05-05 21:17:10 +00003137 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3138 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00003139}
3140
Richard Smith243ef902013-05-05 23:31:59 +00003141static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3142 return T->isSignedIntegerType() &&
3143 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3144}
3145
3146namespace {
Richard Smith43e77732013-05-07 04:50:00 +00003147struct CompoundAssignSubobjectHandler {
3148 EvalInfo &Info;
3149 const Expr *E;
3150 QualType PromotedLHSType;
3151 BinaryOperatorKind Opcode;
3152 const APValue &RHS;
3153
3154 static const AccessKinds AccessKind = AK_Assign;
3155
3156 typedef bool result_type;
3157
3158 bool checkConst(QualType QT) {
3159 // Assigning to a const object has undefined behavior.
3160 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003161 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003162 return false;
3163 }
3164 return true;
3165 }
3166
3167 bool failed() { return false; }
3168 bool found(APValue &Subobj, QualType SubobjType) {
3169 switch (Subobj.getKind()) {
3170 case APValue::Int:
3171 return found(Subobj.getInt(), SubobjType);
3172 case APValue::Float:
3173 return found(Subobj.getFloat(), SubobjType);
3174 case APValue::ComplexInt:
3175 case APValue::ComplexFloat:
3176 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003177 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003178 return false;
3179 case APValue::LValue:
3180 return foundPointer(Subobj, SubobjType);
3181 default:
3182 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003183 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003184 return false;
3185 }
3186 }
3187 bool found(APSInt &Value, QualType SubobjType) {
3188 if (!checkConst(SubobjType))
3189 return false;
3190
3191 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3192 // We don't support compound assignment on integer-cast-to-pointer
3193 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003194 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003195 return false;
3196 }
3197
3198 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3199 SubobjType, Value);
3200 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3201 return false;
3202 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3203 return true;
3204 }
3205 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003206 return checkConst(SubobjType) &&
3207 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3208 Value) &&
3209 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3210 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003211 }
3212 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3213 if (!checkConst(SubobjType))
3214 return false;
3215
3216 QualType PointeeType;
3217 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3218 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003219
3220 if (PointeeType.isNull() || !RHS.isInt() ||
3221 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003222 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003223 return false;
3224 }
3225
Richard Smithd6cc1982017-01-31 02:23:02 +00003226 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003227 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003228 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003229
3230 LValue LVal;
3231 LVal.setFrom(Info.Ctx, Subobj);
3232 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3233 return false;
3234 LVal.moveInto(Subobj);
3235 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003236 }
3237 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3238 llvm_unreachable("shouldn't encounter string elements here");
3239 }
3240};
3241} // end anonymous namespace
3242
3243const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3244
3245/// Perform a compound assignment of LVal <op>= RVal.
3246static bool handleCompoundAssignment(
3247 EvalInfo &Info, const Expr *E,
3248 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3249 BinaryOperatorKind Opcode, const APValue &RVal) {
3250 if (LVal.Designator.Invalid)
3251 return false;
3252
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003253 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003254 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003255 return false;
3256 }
3257
3258 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3259 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3260 RVal };
3261 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3262}
3263
3264namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003265struct IncDecSubobjectHandler {
3266 EvalInfo &Info;
3267 const Expr *E;
3268 AccessKinds AccessKind;
3269 APValue *Old;
3270
3271 typedef bool result_type;
3272
3273 bool checkConst(QualType QT) {
3274 // Assigning to a const object has undefined behavior.
3275 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003276 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003277 return false;
3278 }
3279 return true;
3280 }
3281
3282 bool failed() { return false; }
3283 bool found(APValue &Subobj, QualType SubobjType) {
3284 // Stash the old value. Also clear Old, so we don't clobber it later
3285 // if we're post-incrementing a complex.
3286 if (Old) {
3287 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003288 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003289 }
3290
3291 switch (Subobj.getKind()) {
3292 case APValue::Int:
3293 return found(Subobj.getInt(), SubobjType);
3294 case APValue::Float:
3295 return found(Subobj.getFloat(), SubobjType);
3296 case APValue::ComplexInt:
3297 return found(Subobj.getComplexIntReal(),
3298 SubobjType->castAs<ComplexType>()->getElementType()
3299 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3300 case APValue::ComplexFloat:
3301 return found(Subobj.getComplexFloatReal(),
3302 SubobjType->castAs<ComplexType>()->getElementType()
3303 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3304 case APValue::LValue:
3305 return foundPointer(Subobj, SubobjType);
3306 default:
3307 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003308 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003309 return false;
3310 }
3311 }
3312 bool found(APSInt &Value, QualType SubobjType) {
3313 if (!checkConst(SubobjType))
3314 return false;
3315
3316 if (!SubobjType->isIntegerType()) {
3317 // We don't support increment / decrement on integer-cast-to-pointer
3318 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003319 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003320 return false;
3321 }
3322
3323 if (Old) *Old = APValue(Value);
3324
3325 // bool arithmetic promotes to int, and the conversion back to bool
3326 // doesn't reduce mod 2^n, so special-case it.
3327 if (SubobjType->isBooleanType()) {
3328 if (AccessKind == AK_Increment)
3329 Value = 1;
3330 else
3331 Value = !Value;
3332 return true;
3333 }
3334
3335 bool WasNegative = Value.isNegative();
3336 if (AccessKind == AK_Increment) {
3337 ++Value;
3338
3339 if (!WasNegative && Value.isNegative() &&
3340 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3341 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003342 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003343 }
3344 } else {
3345 --Value;
3346
3347 if (WasNegative && !Value.isNegative() &&
3348 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3349 unsigned BitWidth = Value.getBitWidth();
3350 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3351 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003352 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003353 }
3354 }
3355 return true;
3356 }
3357 bool found(APFloat &Value, QualType SubobjType) {
3358 if (!checkConst(SubobjType))
3359 return false;
3360
3361 if (Old) *Old = APValue(Value);
3362
3363 APFloat One(Value.getSemantics(), 1);
3364 if (AccessKind == AK_Increment)
3365 Value.add(One, APFloat::rmNearestTiesToEven);
3366 else
3367 Value.subtract(One, APFloat::rmNearestTiesToEven);
3368 return true;
3369 }
3370 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3371 if (!checkConst(SubobjType))
3372 return false;
3373
3374 QualType PointeeType;
3375 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3376 PointeeType = PT->getPointeeType();
3377 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003378 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003379 return false;
3380 }
3381
3382 LValue LVal;
3383 LVal.setFrom(Info.Ctx, Subobj);
3384 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3385 AccessKind == AK_Increment ? 1 : -1))
3386 return false;
3387 LVal.moveInto(Subobj);
3388 return true;
3389 }
3390 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3391 llvm_unreachable("shouldn't encounter string elements here");
3392 }
3393};
3394} // end anonymous namespace
3395
3396/// Perform an increment or decrement on LVal.
3397static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3398 QualType LValType, bool IsIncrement, APValue *Old) {
3399 if (LVal.Designator.Invalid)
3400 return false;
3401
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003402 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003403 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003404 return false;
3405 }
3406
3407 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3408 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3409 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3410 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3411}
3412
Richard Smithe97cbd72011-11-11 04:05:33 +00003413/// Build an lvalue for the object argument of a member function call.
3414static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3415 LValue &This) {
3416 if (Object->getType()->isPointerType())
3417 return EvaluatePointer(Object, This, Info);
3418
3419 if (Object->isGLValue())
3420 return EvaluateLValue(Object, This, Info);
3421
Richard Smithd9f663b2013-04-22 15:31:51 +00003422 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003423 return EvaluateTemporary(Object, This, Info);
3424
Faisal Valie690b7a2016-07-02 22:34:24 +00003425 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003426 return false;
3427}
3428
3429/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3430/// lvalue referring to the result.
3431///
3432/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003433/// \param LV - An lvalue referring to the base of the member pointer.
3434/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003435/// \param IncludeMember - Specifies whether the member itself is included in
3436/// the resulting LValue subobject designator. This is not possible when
3437/// creating a bound member function.
3438/// \return The field or method declaration to which the member pointer refers,
3439/// or 0 if evaluation fails.
3440static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003441 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003442 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003443 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003444 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003445 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003446 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003447 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003448
3449 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3450 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003451 if (!MemPtr.getDecl()) {
3452 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003453 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003454 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003455 }
Richard Smith253c2a32012-01-27 01:14:48 +00003456
Richard Smith027bf112011-11-17 22:56:20 +00003457 if (MemPtr.isDerivedMember()) {
3458 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003459 // The end of the derived-to-base path for the base object must match the
3460 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003461 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003462 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003463 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003464 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003465 }
Richard Smith027bf112011-11-17 22:56:20 +00003466 unsigned PathLengthToMember =
3467 LV.Designator.Entries.size() - MemPtr.Path.size();
3468 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3469 const CXXRecordDecl *LVDecl = getAsBaseClass(
3470 LV.Designator.Entries[PathLengthToMember + I]);
3471 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003472 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003473 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003474 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003475 }
Richard Smith027bf112011-11-17 22:56:20 +00003476 }
3477
3478 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003479 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003480 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003481 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003482 } else if (!MemPtr.Path.empty()) {
3483 // Extend the LValue path with the member pointer's path.
3484 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3485 MemPtr.Path.size() + IncludeMember);
3486
3487 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003488 if (const PointerType *PT = LVType->getAs<PointerType>())
3489 LVType = PT->getPointeeType();
3490 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3491 assert(RD && "member pointer access on non-class-type expression");
3492 // The first class in the path is that of the lvalue.
3493 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3494 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003495 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003496 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003497 RD = Base;
3498 }
3499 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003500 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3501 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003502 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003503 }
3504
3505 // Add the member. Note that we cannot build bound member functions here.
3506 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003507 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003508 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003509 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003510 } else if (const IndirectFieldDecl *IFD =
3511 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003512 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003513 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003514 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003515 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003516 }
Richard Smith027bf112011-11-17 22:56:20 +00003517 }
3518
3519 return MemPtr.getDecl();
3520}
3521
Richard Smith84401042013-06-03 05:03:02 +00003522static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3523 const BinaryOperator *BO,
3524 LValue &LV,
3525 bool IncludeMember = true) {
3526 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3527
3528 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003529 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003530 MemberPtr MemPtr;
3531 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3532 }
Craig Topper36250ad2014-05-12 05:36:57 +00003533 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003534 }
3535
3536 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3537 BO->getRHS(), IncludeMember);
3538}
3539
Richard Smith027bf112011-11-17 22:56:20 +00003540/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3541/// the provided lvalue, which currently refers to the base object.
3542static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3543 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003544 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003545 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003546 return false;
3547
Richard Smitha8105bc2012-01-06 16:39:00 +00003548 QualType TargetQT = E->getType();
3549 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3550 TargetQT = PT->getPointeeType();
3551
3552 // Check this cast lands within the final derived-to-base subobject path.
3553 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003554 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003555 << D.MostDerivedType << TargetQT;
3556 return false;
3557 }
3558
Richard Smith027bf112011-11-17 22:56:20 +00003559 // Check the type of the final cast. We don't need to check the path,
3560 // since a cast can only be formed if the path is unique.
3561 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003562 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3563 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003564 if (NewEntriesSize == D.MostDerivedPathLength)
3565 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3566 else
Richard Smith027bf112011-11-17 22:56:20 +00003567 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003568 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003569 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003570 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003571 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003572 }
Richard Smith027bf112011-11-17 22:56:20 +00003573
3574 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003575 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003576}
3577
Mike Stump876387b2009-10-27 22:09:17 +00003578namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003579enum EvalStmtResult {
3580 /// Evaluation failed.
3581 ESR_Failed,
3582 /// Hit a 'return' statement.
3583 ESR_Returned,
3584 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003585 ESR_Succeeded,
3586 /// Hit a 'continue' statement.
3587 ESR_Continue,
3588 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003589 ESR_Break,
3590 /// Still scanning for 'case' or 'default' statement.
3591 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003592};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003593}
Richard Smith254a73d2011-10-28 22:34:42 +00003594
Richard Smith97fcf4b2016-08-14 23:15:52 +00003595static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3596 // We don't need to evaluate the initializer for a static local.
3597 if (!VD->hasLocalStorage())
3598 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003599
Richard Smith97fcf4b2016-08-14 23:15:52 +00003600 LValue Result;
3601 Result.set(VD, Info.CurrentCall->Index);
3602 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003603
Richard Smith97fcf4b2016-08-14 23:15:52 +00003604 const Expr *InitE = VD->getInit();
3605 if (!InitE) {
3606 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3607 << false << VD->getType();
3608 Val = APValue();
3609 return false;
3610 }
Richard Smith51f03172013-06-20 03:00:05 +00003611
Richard Smith97fcf4b2016-08-14 23:15:52 +00003612 if (InitE->isValueDependent())
3613 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003614
Richard Smith97fcf4b2016-08-14 23:15:52 +00003615 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3616 // Wipe out any partially-computed value, to allow tracking that this
3617 // evaluation failed.
3618 Val = APValue();
3619 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003620 }
3621
3622 return true;
3623}
3624
Richard Smith97fcf4b2016-08-14 23:15:52 +00003625static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3626 bool OK = true;
3627
3628 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3629 OK &= EvaluateVarDecl(Info, VD);
3630
3631 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3632 for (auto *BD : DD->bindings())
3633 if (auto *VD = BD->getHoldingVar())
3634 OK &= EvaluateDecl(Info, VD);
3635
3636 return OK;
3637}
3638
3639
Richard Smith4e18ca52013-05-06 05:56:11 +00003640/// Evaluate a condition (either a variable declaration or an expression).
3641static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3642 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003643 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003644 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3645 return false;
3646 return EvaluateAsBooleanCondition(Cond, Result, Info);
3647}
3648
Richard Smith89210072016-04-04 23:29:43 +00003649namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003650/// \brief A location where the result (returned value) of evaluating a
3651/// statement should be stored.
3652struct StmtResult {
3653 /// The APValue that should be filled in with the returned value.
3654 APValue &Value;
3655 /// The location containing the result, if any (used to support RVO).
3656 const LValue *Slot;
3657};
Richard Smith89210072016-04-04 23:29:43 +00003658}
Richard Smith52a980a2015-08-28 02:43:42 +00003659
3660static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003661 const Stmt *S,
3662 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003663
3664/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003665static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003666 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003667 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003668 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003669 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003670 case ESR_Break:
3671 return ESR_Succeeded;
3672 case ESR_Succeeded:
3673 case ESR_Continue:
3674 return ESR_Continue;
3675 case ESR_Failed:
3676 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003677 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003678 return ESR;
3679 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003680 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003681}
3682
Richard Smith496ddcf2013-05-12 17:32:42 +00003683/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003684static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003685 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003686 BlockScopeRAII Scope(Info);
3687
Richard Smith496ddcf2013-05-12 17:32:42 +00003688 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003689 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003690 {
3691 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003692 if (const Stmt *Init = SS->getInit()) {
3693 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3694 if (ESR != ESR_Succeeded)
3695 return ESR;
3696 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003697 if (SS->getConditionVariable() &&
3698 !EvaluateDecl(Info, SS->getConditionVariable()))
3699 return ESR_Failed;
3700 if (!EvaluateInteger(SS->getCond(), Value, Info))
3701 return ESR_Failed;
3702 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003703
3704 // Find the switch case corresponding to the value of the condition.
3705 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003706 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003707 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3708 SC = SC->getNextSwitchCase()) {
3709 if (isa<DefaultStmt>(SC)) {
3710 Found = SC;
3711 continue;
3712 }
3713
3714 const CaseStmt *CS = cast<CaseStmt>(SC);
3715 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3716 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3717 : LHS;
3718 if (LHS <= Value && Value <= RHS) {
3719 Found = SC;
3720 break;
3721 }
3722 }
3723
3724 if (!Found)
3725 return ESR_Succeeded;
3726
3727 // Search the switch body for the switch case and evaluate it from there.
3728 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3729 case ESR_Break:
3730 return ESR_Succeeded;
3731 case ESR_Succeeded:
3732 case ESR_Continue:
3733 case ESR_Failed:
3734 case ESR_Returned:
3735 return ESR;
3736 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003737 // This can only happen if the switch case is nested within a statement
3738 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003739 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003740 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003741 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003742 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003743}
3744
Richard Smith254a73d2011-10-28 22:34:42 +00003745// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003746static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003747 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003748 if (!Info.nextStep(S))
3749 return ESR_Failed;
3750
Richard Smith496ddcf2013-05-12 17:32:42 +00003751 // If we're hunting down a 'case' or 'default' label, recurse through
3752 // substatements until we hit the label.
3753 if (Case) {
3754 // FIXME: We don't start the lifetime of objects whose initialization we
3755 // jump over. However, such objects must be of class type with a trivial
3756 // default constructor that initialize all subobjects, so must be empty,
3757 // so this almost never matters.
3758 switch (S->getStmtClass()) {
3759 case Stmt::CompoundStmtClass:
3760 // FIXME: Precompute which substatement of a compound statement we
3761 // would jump to, and go straight there rather than performing a
3762 // linear scan each time.
3763 case Stmt::LabelStmtClass:
3764 case Stmt::AttributedStmtClass:
3765 case Stmt::DoStmtClass:
3766 break;
3767
3768 case Stmt::CaseStmtClass:
3769 case Stmt::DefaultStmtClass:
3770 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003771 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003772 break;
3773
3774 case Stmt::IfStmtClass: {
3775 // FIXME: Precompute which side of an 'if' we would jump to, and go
3776 // straight there rather than scanning both sides.
3777 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003778
3779 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3780 // preceded by our switch label.
3781 BlockScopeRAII Scope(Info);
3782
Richard Smith496ddcf2013-05-12 17:32:42 +00003783 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3784 if (ESR != ESR_CaseNotFound || !IS->getElse())
3785 return ESR;
3786 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3787 }
3788
3789 case Stmt::WhileStmtClass: {
3790 EvalStmtResult ESR =
3791 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3792 if (ESR != ESR_Continue)
3793 return ESR;
3794 break;
3795 }
3796
3797 case Stmt::ForStmtClass: {
3798 const ForStmt *FS = cast<ForStmt>(S);
3799 EvalStmtResult ESR =
3800 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3801 if (ESR != ESR_Continue)
3802 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003803 if (FS->getInc()) {
3804 FullExpressionRAII IncScope(Info);
3805 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3806 return ESR_Failed;
3807 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003808 break;
3809 }
3810
3811 case Stmt::DeclStmtClass:
3812 // FIXME: If the variable has initialization that can't be jumped over,
3813 // bail out of any immediately-surrounding compound-statement too.
3814 default:
3815 return ESR_CaseNotFound;
3816 }
3817 }
3818
Richard Smith254a73d2011-10-28 22:34:42 +00003819 switch (S->getStmtClass()) {
3820 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003821 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003822 // Don't bother evaluating beyond an expression-statement which couldn't
3823 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003824 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003825 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003826 return ESR_Failed;
3827 return ESR_Succeeded;
3828 }
3829
Faisal Valie690b7a2016-07-02 22:34:24 +00003830 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003831 return ESR_Failed;
3832
3833 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003834 return ESR_Succeeded;
3835
Richard Smithd9f663b2013-04-22 15:31:51 +00003836 case Stmt::DeclStmtClass: {
3837 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003838 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003839 // Each declaration initialization is its own full-expression.
3840 // FIXME: This isn't quite right; if we're performing aggregate
3841 // initialization, each braced subexpression is its own full-expression.
3842 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003843 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003844 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003845 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003846 return ESR_Succeeded;
3847 }
3848
Richard Smith357362d2011-12-13 06:39:58 +00003849 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003850 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003851 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003852 if (RetExpr &&
3853 !(Result.Slot
3854 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3855 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003856 return ESR_Failed;
3857 return ESR_Returned;
3858 }
Richard Smith254a73d2011-10-28 22:34:42 +00003859
3860 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003861 BlockScopeRAII Scope(Info);
3862
Richard Smith254a73d2011-10-28 22:34:42 +00003863 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003864 for (const auto *BI : CS->body()) {
3865 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003866 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003867 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003868 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003869 return ESR;
3870 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003871 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003872 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003873
3874 case Stmt::IfStmtClass: {
3875 const IfStmt *IS = cast<IfStmt>(S);
3876
3877 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003878 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003879 if (const Stmt *Init = IS->getInit()) {
3880 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3881 if (ESR != ESR_Succeeded)
3882 return ESR;
3883 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003884 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003885 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003886 return ESR_Failed;
3887
3888 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3889 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3890 if (ESR != ESR_Succeeded)
3891 return ESR;
3892 }
3893 return ESR_Succeeded;
3894 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003895
3896 case Stmt::WhileStmtClass: {
3897 const WhileStmt *WS = cast<WhileStmt>(S);
3898 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003899 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003900 bool Continue;
3901 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3902 Continue))
3903 return ESR_Failed;
3904 if (!Continue)
3905 break;
3906
3907 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3908 if (ESR != ESR_Continue)
3909 return ESR;
3910 }
3911 return ESR_Succeeded;
3912 }
3913
3914 case Stmt::DoStmtClass: {
3915 const DoStmt *DS = cast<DoStmt>(S);
3916 bool Continue;
3917 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003918 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003919 if (ESR != ESR_Continue)
3920 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003921 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003922
Richard Smith08d6a2c2013-07-24 07:11:57 +00003923 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003924 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3925 return ESR_Failed;
3926 } while (Continue);
3927 return ESR_Succeeded;
3928 }
3929
3930 case Stmt::ForStmtClass: {
3931 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003932 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003933 if (FS->getInit()) {
3934 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3935 if (ESR != ESR_Succeeded)
3936 return ESR;
3937 }
3938 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003939 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003940 bool Continue = true;
3941 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3942 FS->getCond(), Continue))
3943 return ESR_Failed;
3944 if (!Continue)
3945 break;
3946
3947 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3948 if (ESR != ESR_Continue)
3949 return ESR;
3950
Richard Smith08d6a2c2013-07-24 07:11:57 +00003951 if (FS->getInc()) {
3952 FullExpressionRAII IncScope(Info);
3953 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3954 return ESR_Failed;
3955 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003956 }
3957 return ESR_Succeeded;
3958 }
3959
Richard Smith896e0d72013-05-06 06:51:17 +00003960 case Stmt::CXXForRangeStmtClass: {
3961 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003962 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003963
3964 // Initialize the __range variable.
3965 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3966 if (ESR != ESR_Succeeded)
3967 return ESR;
3968
3969 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003970 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3971 if (ESR != ESR_Succeeded)
3972 return ESR;
3973 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003974 if (ESR != ESR_Succeeded)
3975 return ESR;
3976
3977 while (true) {
3978 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003979 {
3980 bool Continue = true;
3981 FullExpressionRAII CondExpr(Info);
3982 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3983 return ESR_Failed;
3984 if (!Continue)
3985 break;
3986 }
Richard Smith896e0d72013-05-06 06:51:17 +00003987
3988 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003989 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003990 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3991 if (ESR != ESR_Succeeded)
3992 return ESR;
3993
3994 // Loop body.
3995 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3996 if (ESR != ESR_Continue)
3997 return ESR;
3998
3999 // Increment: ++__begin
4000 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4001 return ESR_Failed;
4002 }
4003
4004 return ESR_Succeeded;
4005 }
4006
Richard Smith496ddcf2013-05-12 17:32:42 +00004007 case Stmt::SwitchStmtClass:
4008 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4009
Richard Smith4e18ca52013-05-06 05:56:11 +00004010 case Stmt::ContinueStmtClass:
4011 return ESR_Continue;
4012
4013 case Stmt::BreakStmtClass:
4014 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004015
4016 case Stmt::LabelStmtClass:
4017 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4018
4019 case Stmt::AttributedStmtClass:
4020 // As a general principle, C++11 attributes can be ignored without
4021 // any semantic impact.
4022 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4023 Case);
4024
4025 case Stmt::CaseStmtClass:
4026 case Stmt::DefaultStmtClass:
4027 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004028 }
4029}
4030
Richard Smithcc36f692011-12-22 02:22:31 +00004031/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4032/// default constructor. If so, we'll fold it whether or not it's marked as
4033/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4034/// so we need special handling.
4035static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004036 const CXXConstructorDecl *CD,
4037 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004038 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4039 return false;
4040
Richard Smith66e05fe2012-01-18 05:21:49 +00004041 // Value-initialization does not call a trivial default constructor, so such a
4042 // call is a core constant expression whether or not the constructor is
4043 // constexpr.
4044 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004045 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004046 // FIXME: If DiagDecl is an implicitly-declared special member function,
4047 // we should be much more explicit about why it's not constexpr.
4048 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4049 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4050 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004051 } else {
4052 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4053 }
4054 }
4055 return true;
4056}
4057
Richard Smith357362d2011-12-13 06:39:58 +00004058/// CheckConstexprFunction - Check that a function can be called in a constant
4059/// expression.
4060static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4061 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004062 const FunctionDecl *Definition,
4063 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004064 // Potential constant expressions can contain calls to declared, but not yet
4065 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004066 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004067 Declaration->isConstexpr())
4068 return false;
4069
Richard Smith0838f3a2013-05-14 05:18:44 +00004070 // Bail out with no diagnostic if the function declaration itself is invalid.
4071 // We will have produced a relevant diagnostic while parsing it.
4072 if (Declaration->isInvalidDecl())
4073 return false;
4074
Richard Smith357362d2011-12-13 06:39:58 +00004075 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004076 if (Definition && Definition->isConstexpr() &&
4077 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004078 return true;
4079
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004080 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004081 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Faisal Valie690b7a2016-07-02 22:34:24 +00004082
Richard Smith5179eb72016-06-28 19:03:57 +00004083 // If this function is not constexpr because it is an inherited
4084 // non-constexpr constructor, diagnose that directly.
4085 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4086 if (CD && CD->isInheritingConstructor()) {
4087 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4088 if (!Inherited->isConstexpr())
4089 DiagDecl = CD = Inherited;
4090 }
4091
4092 // FIXME: If DiagDecl is an implicitly-declared special member function
4093 // or an inheriting constructor, we should be much more explicit about why
4094 // it's not constexpr.
4095 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004096 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004097 << CD->getInheritedConstructor().getConstructor()->getParent();
4098 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004099 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004100 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004101 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4102 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004103 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004104 }
4105 return false;
4106}
4107
Richard Smithbe6dd812014-11-19 21:27:17 +00004108/// Determine if a class has any fields that might need to be copied by a
4109/// trivial copy or move operation.
4110static bool hasFields(const CXXRecordDecl *RD) {
4111 if (!RD || RD->isEmpty())
4112 return false;
4113 for (auto *FD : RD->fields()) {
4114 if (FD->isUnnamedBitfield())
4115 continue;
4116 return true;
4117 }
4118 for (auto &Base : RD->bases())
4119 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4120 return true;
4121 return false;
4122}
4123
Richard Smithd62306a2011-11-10 06:34:14 +00004124namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004125typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004126}
4127
4128/// EvaluateArgs - Evaluate the arguments to a function call.
4129static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4130 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004131 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004132 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004133 I != E; ++I) {
4134 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4135 // If we're checking for a potential constant expression, evaluate all
4136 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004137 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004138 return false;
4139 Success = false;
4140 }
4141 }
4142 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004143}
4144
Richard Smith254a73d2011-10-28 22:34:42 +00004145/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004146static bool HandleFunctionCall(SourceLocation CallLoc,
4147 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004148 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004149 EvalInfo &Info, APValue &Result,
4150 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004151 ArgVector ArgValues(Args.size());
4152 if (!EvaluateArgs(Args, ArgValues, Info))
4153 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004154
Richard Smith253c2a32012-01-27 01:14:48 +00004155 if (!Info.CheckCallLimit(CallLoc))
4156 return false;
4157
4158 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004159
4160 // For a trivial copy or move assignment, perform an APValue copy. This is
4161 // essential for unions, where the operations performed by the assignment
4162 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004163 //
4164 // Skip this for non-union classes with no fields; in that case, the defaulted
4165 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004166 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004167 if (MD && MD->isDefaulted() &&
4168 (MD->getParent()->isUnion() ||
4169 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004170 assert(This &&
4171 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4172 LValue RHS;
4173 RHS.setFrom(Info.Ctx, ArgValues[0]);
4174 APValue RHSValue;
4175 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4176 RHS, RHSValue))
4177 return false;
4178 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4179 RHSValue))
4180 return false;
4181 This->moveInto(Result);
4182 return true;
4183 }
4184
Richard Smith52a980a2015-08-28 02:43:42 +00004185 StmtResult Ret = {Result, ResultSlot};
4186 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004187 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004188 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004189 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004190 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004191 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004192 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004193}
4194
Richard Smithd62306a2011-11-10 06:34:14 +00004195/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004196static bool HandleConstructorCall(const Expr *E, const LValue &This,
4197 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004198 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004199 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004200 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004201 if (!Info.CheckCallLimit(CallLoc))
4202 return false;
4203
Richard Smith3607ffe2012-02-13 03:54:03 +00004204 const CXXRecordDecl *RD = Definition->getParent();
4205 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004206 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004207 return false;
4208 }
4209
Richard Smith5179eb72016-06-28 19:03:57 +00004210 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004211
Richard Smith52a980a2015-08-28 02:43:42 +00004212 // FIXME: Creating an APValue just to hold a nonexistent return value is
4213 // wasteful.
4214 APValue RetVal;
4215 StmtResult Ret = {RetVal, nullptr};
4216
Richard Smith5179eb72016-06-28 19:03:57 +00004217 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004218 if (Definition->isDelegatingConstructor()) {
4219 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004220 {
4221 FullExpressionRAII InitScope(Info);
4222 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4223 return false;
4224 }
Richard Smith52a980a2015-08-28 02:43:42 +00004225 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004226 }
4227
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004228 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004229 // essential for unions (or classes with anonymous union members), where the
4230 // operations performed by the constructor cannot be represented by
4231 // ctor-initializers.
4232 //
4233 // Skip this for empty non-union classes; we should not perform an
4234 // lvalue-to-rvalue conversion on them because their copy constructor does not
4235 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004236 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004237 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004238 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004239 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004240 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004241 return handleLValueToRValueConversion(
4242 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4243 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004244 }
4245
4246 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004247 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004248 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004249 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004250
John McCalld7bca762012-05-01 00:38:49 +00004251 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004252 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4253
Richard Smith08d6a2c2013-07-24 07:11:57 +00004254 // A scope for temporaries lifetime-extended by reference members.
4255 BlockScopeRAII LifetimeExtendedScope(Info);
4256
Richard Smith253c2a32012-01-27 01:14:48 +00004257 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004258 unsigned BasesSeen = 0;
4259#ifndef NDEBUG
4260 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4261#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004262 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004263 LValue Subobject = This;
4264 APValue *Value = &Result;
4265
4266 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004267 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004268 if (I->isBaseInitializer()) {
4269 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004270#ifndef NDEBUG
4271 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004272 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004273 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4274 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4275 "base class initializers not in expected order");
4276 ++BaseIt;
4277#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004278 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004279 BaseType->getAsCXXRecordDecl(), &Layout))
4280 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004281 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004282 } else if ((FD = I->getMember())) {
4283 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004284 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004285 if (RD->isUnion()) {
4286 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004287 Value = &Result.getUnionValue();
4288 } else {
4289 Value = &Result.getStructField(FD->getFieldIndex());
4290 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004291 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004292 // Walk the indirect field decl's chain to find the object to initialize,
4293 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004294 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004295 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004296 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4297 // Switch the union field if it differs. This happens if we had
4298 // preceding zero-initialization, and we're now initializing a union
4299 // subobject other than the first.
4300 // FIXME: In this case, the values of the other subobjects are
4301 // specified, since zero-initialization sets all padding bits to zero.
4302 if (Value->isUninit() ||
4303 (Value->isUnion() && Value->getUnionField() != FD)) {
4304 if (CD->isUnion())
4305 *Value = APValue(FD);
4306 else
4307 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004308 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004309 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004310 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004311 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004312 if (CD->isUnion())
4313 Value = &Value->getUnionValue();
4314 else
4315 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004316 }
Richard Smithd62306a2011-11-10 06:34:14 +00004317 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004318 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004319 }
Richard Smith253c2a32012-01-27 01:14:48 +00004320
Richard Smith08d6a2c2013-07-24 07:11:57 +00004321 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004322 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4323 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004324 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004325 // If we're checking for a potential constant expression, evaluate all
4326 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004327 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004328 return false;
4329 Success = false;
4330 }
Richard Smithd62306a2011-11-10 06:34:14 +00004331 }
4332
Richard Smithd9f663b2013-04-22 15:31:51 +00004333 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004334 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004335}
4336
Richard Smith5179eb72016-06-28 19:03:57 +00004337static bool HandleConstructorCall(const Expr *E, const LValue &This,
4338 ArrayRef<const Expr*> Args,
4339 const CXXConstructorDecl *Definition,
4340 EvalInfo &Info, APValue &Result) {
4341 ArgVector ArgValues(Args.size());
4342 if (!EvaluateArgs(Args, ArgValues, Info))
4343 return false;
4344
4345 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4346 Info, Result);
4347}
4348
Eli Friedman9a156e52008-11-12 09:44:48 +00004349//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004350// Generic Evaluation
4351//===----------------------------------------------------------------------===//
4352namespace {
4353
Aaron Ballman68af21c2014-01-03 19:26:43 +00004354template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004355class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004356 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004357private:
Richard Smith52a980a2015-08-28 02:43:42 +00004358 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004359 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004360 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004361 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004362 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004363 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004364 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004365
Richard Smith17100ba2012-02-16 02:46:34 +00004366 // Check whether a conditional operator with a non-constant condition is a
4367 // potential constant expression. If neither arm is a potential constant
4368 // expression, then the conditional operator is not either.
4369 template<typename ConditionalOperator>
4370 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004371 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004372
4373 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004374 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004375 {
Richard Smith17100ba2012-02-16 02:46:34 +00004376 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004377 StmtVisitorTy::Visit(E->getFalseExpr());
4378 if (Diag.empty())
4379 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004380 }
Richard Smith17100ba2012-02-16 02:46:34 +00004381
George Burgess IV8c892b52016-05-25 22:31:54 +00004382 {
4383 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004384 Diag.clear();
4385 StmtVisitorTy::Visit(E->getTrueExpr());
4386 if (Diag.empty())
4387 return;
4388 }
4389
4390 Error(E, diag::note_constexpr_conditional_never_const);
4391 }
4392
4393
4394 template<typename ConditionalOperator>
4395 bool HandleConditionalOperator(const ConditionalOperator *E) {
4396 bool BoolResult;
4397 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004398 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004399 CheckPotentialConstantConditional(E);
4400 return false;
4401 }
4402
4403 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4404 return StmtVisitorTy::Visit(EvalExpr);
4405 }
4406
Peter Collingbournee9200682011-05-13 03:29:01 +00004407protected:
4408 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004409 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004410 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4411
Richard Smith92b1ce02011-12-12 09:28:41 +00004412 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004413 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004414 }
4415
Aaron Ballman68af21c2014-01-03 19:26:43 +00004416 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004417
4418public:
4419 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4420
4421 EvalInfo &getEvalInfo() { return Info; }
4422
Richard Smithf57d8cb2011-12-09 22:58:01 +00004423 /// Report an evaluation error. This should only be called when an error is
4424 /// first discovered. When propagating an error, just return false.
4425 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004426 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004427 return false;
4428 }
4429 bool Error(const Expr *E) {
4430 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4431 }
4432
Aaron Ballman68af21c2014-01-03 19:26:43 +00004433 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004434 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004435 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004436 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004437 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004438 }
4439
Aaron Ballman68af21c2014-01-03 19:26:43 +00004440 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004441 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004442 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004443 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004444 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004445 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004446 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004447 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004448 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004449 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004450 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004451 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004452 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004453 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004454 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004455 // The initializer may not have been parsed yet, or might be erroneous.
4456 if (!E->getExpr())
4457 return Error(E);
4458 return StmtVisitorTy::Visit(E->getExpr());
4459 }
Richard Smith5894a912011-12-19 22:12:41 +00004460 // We cannot create any objects for which cleanups are required, so there is
4461 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004462 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004463 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004464
Aaron Ballman68af21c2014-01-03 19:26:43 +00004465 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004466 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4467 return static_cast<Derived*>(this)->VisitCastExpr(E);
4468 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004469 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004470 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4471 return static_cast<Derived*>(this)->VisitCastExpr(E);
4472 }
4473
Aaron Ballman68af21c2014-01-03 19:26:43 +00004474 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004475 switch (E->getOpcode()) {
4476 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004477 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004478
4479 case BO_Comma:
4480 VisitIgnoredValue(E->getLHS());
4481 return StmtVisitorTy::Visit(E->getRHS());
4482
4483 case BO_PtrMemD:
4484 case BO_PtrMemI: {
4485 LValue Obj;
4486 if (!HandleMemberPointerAccess(Info, E, Obj))
4487 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004488 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004489 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004490 return false;
4491 return DerivedSuccess(Result, E);
4492 }
4493 }
4494 }
4495
Aaron Ballman68af21c2014-01-03 19:26:43 +00004496 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004497 // Evaluate and cache the common expression. We treat it as a temporary,
4498 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004499 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004500 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004501 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004502
Richard Smith17100ba2012-02-16 02:46:34 +00004503 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004504 }
4505
Aaron Ballman68af21c2014-01-03 19:26:43 +00004506 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004507 bool IsBcpCall = false;
4508 // If the condition (ignoring parens) is a __builtin_constant_p call,
4509 // the result is a constant expression if it can be folded without
4510 // side-effects. This is an important GNU extension. See GCC PR38377
4511 // for discussion.
4512 if (const CallExpr *CallCE =
4513 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004514 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004515 IsBcpCall = true;
4516
4517 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4518 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004519 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004520 return false;
4521
Richard Smith6d4c6582013-11-05 22:18:15 +00004522 FoldConstant Fold(Info, IsBcpCall);
4523 if (!HandleConditionalOperator(E)) {
4524 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004525 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004526 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004527
4528 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004529 }
4530
Aaron Ballman68af21c2014-01-03 19:26:43 +00004531 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004532 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4533 return DerivedSuccess(*Value, E);
4534
4535 const Expr *Source = E->getSourceExpr();
4536 if (!Source)
4537 return Error(E);
4538 if (Source == E) { // sanity checking.
4539 assert(0 && "OpaqueValueExpr recursively refers to itself");
4540 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004541 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004542 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004543 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004544
Aaron Ballman68af21c2014-01-03 19:26:43 +00004545 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004546 APValue Result;
4547 if (!handleCallExpr(E, Result, nullptr))
4548 return false;
4549 return DerivedSuccess(Result, E);
4550 }
4551
4552 bool handleCallExpr(const CallExpr *E, APValue &Result,
4553 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004554 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004555 QualType CalleeType = Callee->getType();
4556
Craig Topper36250ad2014-05-12 05:36:57 +00004557 const FunctionDecl *FD = nullptr;
4558 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004559 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004560 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004561
Richard Smithe97cbd72011-11-11 04:05:33 +00004562 // Extract function decl and 'this' pointer from the callee.
4563 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004564 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004565 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4566 // Explicit bound member calls, such as x.f() or p->g();
4567 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004568 return false;
4569 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004570 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004571 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004572 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4573 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004574 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4575 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004576 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004577 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004578 return Error(Callee);
4579
4580 FD = dyn_cast<FunctionDecl>(Member);
4581 if (!FD)
4582 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004583 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004584 LValue Call;
4585 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004586 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004587
Richard Smitha8105bc2012-01-06 16:39:00 +00004588 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004589 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004590 FD = dyn_cast_or_null<FunctionDecl>(
4591 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004592 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004593 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004594 // Don't call function pointers which have been cast to some other type.
4595 // Per DR (no number yet), the caller and callee can differ in noexcept.
4596 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4597 CalleeType->getPointeeType(), FD->getType())) {
4598 return Error(E);
4599 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004600
4601 // Overloaded operator calls to member functions are represented as normal
4602 // calls with '*this' as the first argument.
4603 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4604 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004605 // FIXME: When selecting an implicit conversion for an overloaded
4606 // operator delete, we sometimes try to evaluate calls to conversion
4607 // operators without a 'this' parameter!
4608 if (Args.empty())
4609 return Error(E);
4610
Richard Smithe97cbd72011-11-11 04:05:33 +00004611 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4612 return false;
4613 This = &ThisVal;
4614 Args = Args.slice(1);
Faisal Valid92e7492017-01-08 18:56:11 +00004615 } else if (MD && MD->isLambdaStaticInvoker()) {
4616 // Map the static invoker for the lambda back to the call operator.
4617 // Conveniently, we don't have to slice out the 'this' argument (as is
4618 // being done for the non-static case), since a static member function
4619 // doesn't have an implicit argument passed in.
4620 const CXXRecordDecl *ClosureClass = MD->getParent();
4621 assert(
4622 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4623 "Number of captures must be zero for conversion to function-ptr");
4624
4625 const CXXMethodDecl *LambdaCallOp =
4626 ClosureClass->getLambdaCallOperator();
4627
4628 // Set 'FD', the function that will be called below, to the call
4629 // operator. If the closure object represents a generic lambda, find
4630 // the corresponding specialization of the call operator.
4631
4632 if (ClosureClass->isGenericLambda()) {
4633 assert(MD->isFunctionTemplateSpecialization() &&
4634 "A generic lambda's static-invoker function must be a "
4635 "template specialization");
4636 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4637 FunctionTemplateDecl *CallOpTemplate =
4638 LambdaCallOp->getDescribedFunctionTemplate();
4639 void *InsertPos = nullptr;
4640 FunctionDecl *CorrespondingCallOpSpecialization =
4641 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4642 assert(CorrespondingCallOpSpecialization &&
4643 "We must always have a function call operator specialization "
4644 "that corresponds to our static invoker specialization");
4645 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4646 } else
4647 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004648 }
4649
Faisal Valid92e7492017-01-08 18:56:11 +00004650
Richard Smithe97cbd72011-11-11 04:05:33 +00004651 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004652 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004653
Richard Smith47b34932012-02-01 02:39:43 +00004654 if (This && !This->checkSubobject(Info, E, CSK_This))
4655 return false;
4656
Richard Smith3607ffe2012-02-13 03:54:03 +00004657 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4658 // calls to such functions in constant expressions.
4659 if (This && !HasQualifier &&
4660 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4661 return Error(E, diag::note_constexpr_virtual_call);
4662
Craig Topper36250ad2014-05-12 05:36:57 +00004663 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004664 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004665
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004666 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004667 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4668 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004669 return false;
4670
Richard Smith52a980a2015-08-28 02:43:42 +00004671 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004672 }
4673
Aaron Ballman68af21c2014-01-03 19:26:43 +00004674 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004675 return StmtVisitorTy::Visit(E->getInitializer());
4676 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004677 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004678 if (E->getNumInits() == 0)
4679 return DerivedZeroInitialization(E);
4680 if (E->getNumInits() == 1)
4681 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004682 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004683 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004684 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004685 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004686 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004687 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004688 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004689 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004690 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004691 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004692 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004693
Richard Smithd62306a2011-11-10 06:34:14 +00004694 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004695 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004696 assert(!E->isArrow() && "missing call to bound member function?");
4697
Richard Smith2e312c82012-03-03 22:46:17 +00004698 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004699 if (!Evaluate(Val, Info, E->getBase()))
4700 return false;
4701
4702 QualType BaseTy = E->getBase()->getType();
4703
4704 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004705 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004706 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004707 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004708 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4709
Richard Smith3229b742013-05-05 21:17:10 +00004710 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004711 SubobjectDesignator Designator(BaseTy);
4712 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004713
Richard Smith3229b742013-05-05 21:17:10 +00004714 APValue Result;
4715 return extractSubobject(Info, E, Obj, Designator, Result) &&
4716 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004717 }
4718
Aaron Ballman68af21c2014-01-03 19:26:43 +00004719 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004720 switch (E->getCastKind()) {
4721 default:
4722 break;
4723
Richard Smitha23ab512013-05-23 00:30:41 +00004724 case CK_AtomicToNonAtomic: {
4725 APValue AtomicVal;
4726 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4727 return false;
4728 return DerivedSuccess(AtomicVal, E);
4729 }
4730
Richard Smith11562c52011-10-28 17:51:58 +00004731 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004732 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004733 return StmtVisitorTy::Visit(E->getSubExpr());
4734
4735 case CK_LValueToRValue: {
4736 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004737 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4738 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004739 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004740 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004741 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004742 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004743 return false;
4744 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004745 }
4746 }
4747
Richard Smithf57d8cb2011-12-09 22:58:01 +00004748 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004749 }
4750
Aaron Ballman68af21c2014-01-03 19:26:43 +00004751 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004752 return VisitUnaryPostIncDec(UO);
4753 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004754 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004755 return VisitUnaryPostIncDec(UO);
4756 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004757 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004758 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004759 return Error(UO);
4760
4761 LValue LVal;
4762 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4763 return false;
4764 APValue RVal;
4765 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4766 UO->isIncrementOp(), &RVal))
4767 return false;
4768 return DerivedSuccess(RVal, UO);
4769 }
4770
Aaron Ballman68af21c2014-01-03 19:26:43 +00004771 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004772 // We will have checked the full-expressions inside the statement expression
4773 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004774 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004775 return Error(E);
4776
Richard Smith08d6a2c2013-07-24 07:11:57 +00004777 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004778 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004779 if (CS->body_empty())
4780 return true;
4781
Richard Smith51f03172013-06-20 03:00:05 +00004782 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4783 BE = CS->body_end();
4784 /**/; ++BI) {
4785 if (BI + 1 == BE) {
4786 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4787 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004788 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004789 diag::note_constexpr_stmt_expr_unsupported);
4790 return false;
4791 }
4792 return this->Visit(FinalExpr);
4793 }
4794
4795 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004796 StmtResult Result = { ReturnValue, nullptr };
4797 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004798 if (ESR != ESR_Succeeded) {
4799 // FIXME: If the statement-expression terminated due to 'return',
4800 // 'break', or 'continue', it would be nice to propagate that to
4801 // the outer statement evaluation rather than bailing out.
4802 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004803 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004804 diag::note_constexpr_stmt_expr_unsupported);
4805 return false;
4806 }
4807 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004808
4809 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004810 }
4811
Richard Smith4a678122011-10-24 18:44:57 +00004812 /// Visit a value which is evaluated, but whose value is ignored.
4813 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004814 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004815 }
David Majnemere9807b22016-02-26 04:23:19 +00004816
4817 /// Potentially visit a MemberExpr's base expression.
4818 void VisitIgnoredBaseExpression(const Expr *E) {
4819 // While MSVC doesn't evaluate the base expression, it does diagnose the
4820 // presence of side-effecting behavior.
4821 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4822 return;
4823 VisitIgnoredValue(E);
4824 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004825};
4826
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004827}
Peter Collingbournee9200682011-05-13 03:29:01 +00004828
4829//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004830// Common base class for lvalue and temporary evaluation.
4831//===----------------------------------------------------------------------===//
4832namespace {
4833template<class Derived>
4834class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004835 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004836protected:
4837 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00004838 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00004839 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004840 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004841
4842 bool Success(APValue::LValueBase B) {
4843 Result.set(B);
4844 return true;
4845 }
4846
George Burgess IVf9013bf2017-02-10 22:52:29 +00004847 bool evaluatePointer(const Expr *E, LValue &Result) {
4848 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4849 }
4850
Richard Smith027bf112011-11-17 22:56:20 +00004851public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004852 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4853 : ExprEvaluatorBaseTy(Info), Result(Result),
4854 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00004855
Richard Smith2e312c82012-03-03 22:46:17 +00004856 bool Success(const APValue &V, const Expr *E) {
4857 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004858 return true;
4859 }
Richard Smith027bf112011-11-17 22:56:20 +00004860
Richard Smith027bf112011-11-17 22:56:20 +00004861 bool VisitMemberExpr(const MemberExpr *E) {
4862 // Handle non-static data members.
4863 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004864 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004865 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004866 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00004867 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004868 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004869 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004870 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004871 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004872 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004873 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004874 BaseTy = E->getBase()->getType();
4875 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004876 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004877 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004878 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004879 Result.setInvalid(E);
4880 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004881 }
Richard Smith027bf112011-11-17 22:56:20 +00004882
Richard Smith1b78b3d2012-01-25 22:15:11 +00004883 const ValueDecl *MD = E->getMemberDecl();
4884 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4885 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4886 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4887 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004888 if (!HandleLValueMember(this->Info, E, Result, FD))
4889 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004890 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004891 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4892 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004893 } else
4894 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004895
Richard Smith1b78b3d2012-01-25 22:15:11 +00004896 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004897 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004898 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004899 RefValue))
4900 return false;
4901 return Success(RefValue, E);
4902 }
4903 return true;
4904 }
4905
4906 bool VisitBinaryOperator(const BinaryOperator *E) {
4907 switch (E->getOpcode()) {
4908 default:
4909 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4910
4911 case BO_PtrMemD:
4912 case BO_PtrMemI:
4913 return HandleMemberPointerAccess(this->Info, E, Result);
4914 }
4915 }
4916
4917 bool VisitCastExpr(const CastExpr *E) {
4918 switch (E->getCastKind()) {
4919 default:
4920 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4921
4922 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004923 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004924 if (!this->Visit(E->getSubExpr()))
4925 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004926
4927 // Now figure out the necessary offset to add to the base LV to get from
4928 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004929 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4930 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004931 }
4932 }
4933};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004934}
Richard Smith027bf112011-11-17 22:56:20 +00004935
4936//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004937// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004938//
4939// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4940// function designators (in C), decl references to void objects (in C), and
4941// temporaries (if building with -Wno-address-of-temporary).
4942//
4943// LValue evaluation produces values comprising a base expression of one of the
4944// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004945// - Declarations
4946// * VarDecl
4947// * FunctionDecl
4948// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00004949// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00004950// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004951// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004952// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004953// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004954// * ObjCEncodeExpr
4955// * AddrLabelExpr
4956// * BlockExpr
4957// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004958// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004959// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004960// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004961// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4962// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004963// * A MaterializeTemporaryExpr that has static storage duration, with no
4964// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004965// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004966//===----------------------------------------------------------------------===//
4967namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004968class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004969 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004970public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004971 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
4972 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00004973
Richard Smith11562c52011-10-28 17:51:58 +00004974 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004975 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004976
Peter Collingbournee9200682011-05-13 03:29:01 +00004977 bool VisitDeclRefExpr(const DeclRefExpr *E);
4978 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004979 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004980 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4981 bool VisitMemberExpr(const MemberExpr *E);
4982 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4983 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004984 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004985 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004986 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4987 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004988 bool VisitUnaryReal(const UnaryOperator *E);
4989 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004990 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4991 return VisitUnaryPreIncDec(UO);
4992 }
4993 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4994 return VisitUnaryPreIncDec(UO);
4995 }
Richard Smith3229b742013-05-05 21:17:10 +00004996 bool VisitBinAssign(const BinaryOperator *BO);
4997 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004998
Peter Collingbournee9200682011-05-13 03:29:01 +00004999 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005000 switch (E->getCastKind()) {
5001 default:
Richard Smith027bf112011-11-17 22:56:20 +00005002 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005003
Eli Friedmance3e02a2011-10-11 00:13:24 +00005004 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005005 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005006 if (!Visit(E->getSubExpr()))
5007 return false;
5008 Result.Designator.setInvalid();
5009 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005010
Richard Smith027bf112011-11-17 22:56:20 +00005011 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005012 if (!Visit(E->getSubExpr()))
5013 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005014 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005015 }
5016 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005017};
5018} // end anonymous namespace
5019
Richard Smith11562c52011-10-28 17:51:58 +00005020/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005021/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005022/// * function designators in C, and
5023/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005024/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005025static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5026 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005027 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005028 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005029 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005030}
5031
Peter Collingbournee9200682011-05-13 03:29:01 +00005032bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005033 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005034 return Success(FD);
5035 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005036 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005037 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005038 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005039 return Error(E);
5040}
Richard Smith733237d2011-10-24 23:14:33 +00005041
Faisal Vali0528a312016-11-13 06:09:16 +00005042
Richard Smith11562c52011-10-28 17:51:58 +00005043bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00005044 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005045 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5046 // Only if a local variable was declared in the function currently being
5047 // evaluated, do we expect to be able to find its value in the current
5048 // frame. (Otherwise it was likely declared in an enclosing context and
5049 // could either have a valid evaluatable value (for e.g. a constexpr
5050 // variable) or be ill-formed (and trigger an appropriate evaluation
5051 // diagnostic)).
5052 if (Info.CurrentCall->Callee &&
5053 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5054 Frame = Info.CurrentCall;
5055 }
5056 }
Richard Smith3229b742013-05-05 21:17:10 +00005057
Richard Smithfec09922011-11-01 16:57:24 +00005058 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005059 if (Frame) {
5060 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005061 return true;
5062 }
Richard Smithce40ad62011-11-12 22:28:03 +00005063 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005064 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005065
Richard Smith3229b742013-05-05 21:17:10 +00005066 APValue *V;
5067 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005068 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005069 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005070 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005071 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005072 return false;
5073 }
Richard Smith3229b742013-05-05 21:17:10 +00005074 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005075}
5076
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005077bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5078 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005079 // Walk through the expression to find the materialized temporary itself.
5080 SmallVector<const Expr *, 2> CommaLHSs;
5081 SmallVector<SubobjectAdjustment, 2> Adjustments;
5082 const Expr *Inner = E->GetTemporaryExpr()->
5083 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005084
Richard Smith84401042013-06-03 05:03:02 +00005085 // If we passed any comma operators, evaluate their LHSs.
5086 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5087 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5088 return false;
5089
Richard Smithe6c01442013-06-05 00:46:14 +00005090 // A materialized temporary with static storage duration can appear within the
5091 // result of a constant expression evaluation, so we need to preserve its
5092 // value for use outside this evaluation.
5093 APValue *Value;
5094 if (E->getStorageDuration() == SD_Static) {
5095 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005096 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005097 Result.set(E);
5098 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005099 Value = &Info.CurrentCall->
5100 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005101 Result.set(E, Info.CurrentCall->Index);
5102 }
5103
Richard Smithea4ad5d2013-06-06 08:19:16 +00005104 QualType Type = Inner->getType();
5105
Richard Smith84401042013-06-03 05:03:02 +00005106 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005107 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5108 (E->getStorageDuration() == SD_Static &&
5109 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5110 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005111 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005112 }
Richard Smith84401042013-06-03 05:03:02 +00005113
5114 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005115 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5116 --I;
5117 switch (Adjustments[I].Kind) {
5118 case SubobjectAdjustment::DerivedToBaseAdjustment:
5119 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5120 Type, Result))
5121 return false;
5122 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5123 break;
5124
5125 case SubobjectAdjustment::FieldAdjustment:
5126 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5127 return false;
5128 Type = Adjustments[I].Field->getType();
5129 break;
5130
5131 case SubobjectAdjustment::MemberPointerAdjustment:
5132 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5133 Adjustments[I].Ptr.RHS))
5134 return false;
5135 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5136 break;
5137 }
5138 }
5139
5140 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005141}
5142
Peter Collingbournee9200682011-05-13 03:29:01 +00005143bool
5144LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005145 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5146 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005147 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5148 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005149 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005150}
5151
Richard Smith6e525142011-12-27 12:18:28 +00005152bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005153 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005154 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005155
Faisal Valie690b7a2016-07-02 22:34:24 +00005156 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005157 << E->getExprOperand()->getType()
5158 << E->getExprOperand()->getSourceRange();
5159 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005160}
5161
Francois Pichet0066db92012-04-16 04:08:35 +00005162bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5163 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005164}
Francois Pichet0066db92012-04-16 04:08:35 +00005165
Peter Collingbournee9200682011-05-13 03:29:01 +00005166bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005167 // Handle static data members.
5168 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005169 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005170 return VisitVarDecl(E, VD);
5171 }
5172
Richard Smith254a73d2011-10-28 22:34:42 +00005173 // Handle static member functions.
5174 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5175 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005176 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005177 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005178 }
5179 }
5180
Richard Smithd62306a2011-11-10 06:34:14 +00005181 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005182 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005183}
5184
Peter Collingbournee9200682011-05-13 03:29:01 +00005185bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005186 // FIXME: Deal with vectors as array subscript bases.
5187 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005188 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005189
George Burgess IVf9013bf2017-02-10 22:52:29 +00005190 if (!evaluatePointer(E->getBase(), Result))
John McCall45d55e42010-05-07 21:00:08 +00005191 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005192
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005193 APSInt Index;
5194 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005195 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005196
Richard Smithd6cc1982017-01-31 02:23:02 +00005197 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005198}
Eli Friedman9a156e52008-11-12 09:44:48 +00005199
Peter Collingbournee9200682011-05-13 03:29:01 +00005200bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005201 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005202}
5203
Richard Smith66c96992012-02-18 22:04:06 +00005204bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5205 if (!Visit(E->getSubExpr()))
5206 return false;
5207 // __real is a no-op on scalar lvalues.
5208 if (E->getSubExpr()->getType()->isAnyComplexType())
5209 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5210 return true;
5211}
5212
5213bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5214 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5215 "lvalue __imag__ on scalar?");
5216 if (!Visit(E->getSubExpr()))
5217 return false;
5218 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5219 return true;
5220}
5221
Richard Smith243ef902013-05-05 23:31:59 +00005222bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005223 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005224 return Error(UO);
5225
5226 if (!this->Visit(UO->getSubExpr()))
5227 return false;
5228
Richard Smith243ef902013-05-05 23:31:59 +00005229 return handleIncDec(
5230 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005231 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005232}
5233
5234bool LValueExprEvaluator::VisitCompoundAssignOperator(
5235 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005236 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005237 return Error(CAO);
5238
Richard Smith3229b742013-05-05 21:17:10 +00005239 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005240
5241 // The overall lvalue result is the result of evaluating the LHS.
5242 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005243 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005244 Evaluate(RHS, this->Info, CAO->getRHS());
5245 return false;
5246 }
5247
Richard Smith3229b742013-05-05 21:17:10 +00005248 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5249 return false;
5250
Richard Smith43e77732013-05-07 04:50:00 +00005251 return handleCompoundAssignment(
5252 this->Info, CAO,
5253 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5254 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005255}
5256
5257bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005258 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005259 return Error(E);
5260
Richard Smith3229b742013-05-05 21:17:10 +00005261 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005262
5263 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005264 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005265 Evaluate(NewVal, this->Info, E->getRHS());
5266 return false;
5267 }
5268
Richard Smith3229b742013-05-05 21:17:10 +00005269 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5270 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005271
5272 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005273 NewVal);
5274}
5275
Eli Friedman9a156e52008-11-12 09:44:48 +00005276//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005277// Pointer Evaluation
5278//===----------------------------------------------------------------------===//
5279
George Burgess IVe3763372016-12-22 02:50:20 +00005280/// \brief Attempts to compute the number of bytes available at the pointer
5281/// returned by a function with the alloc_size attribute. Returns true if we
5282/// were successful. Places an unsigned number into `Result`.
5283///
5284/// This expects the given CallExpr to be a call to a function with an
5285/// alloc_size attribute.
5286static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5287 const CallExpr *Call,
5288 llvm::APInt &Result) {
5289 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5290
5291 // alloc_size args are 1-indexed, 0 means not present.
5292 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5293 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5294 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5295 if (Call->getNumArgs() <= SizeArgNo)
5296 return false;
5297
5298 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5299 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5300 return false;
5301 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5302 return false;
5303 Into = Into.zextOrSelf(BitsInSizeT);
5304 return true;
5305 };
5306
5307 APSInt SizeOfElem;
5308 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5309 return false;
5310
5311 if (!AllocSize->getNumElemsParam()) {
5312 Result = std::move(SizeOfElem);
5313 return true;
5314 }
5315
5316 APSInt NumberOfElems;
5317 // Argument numbers start at 1
5318 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5319 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5320 return false;
5321
5322 bool Overflow;
5323 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5324 if (Overflow)
5325 return false;
5326
5327 Result = std::move(BytesAvailable);
5328 return true;
5329}
5330
5331/// \brief Convenience function. LVal's base must be a call to an alloc_size
5332/// function.
5333static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5334 const LValue &LVal,
5335 llvm::APInt &Result) {
5336 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5337 "Can't get the size of a non alloc_size function");
5338 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5339 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5340 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5341}
5342
5343/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5344/// a function with the alloc_size attribute. If it was possible to do so, this
5345/// function will return true, make Result's Base point to said function call,
5346/// and mark Result's Base as invalid.
5347static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5348 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005349 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005350 return false;
5351
5352 // Because we do no form of static analysis, we only support const variables.
5353 //
5354 // Additionally, we can't support parameters, nor can we support static
5355 // variables (in the latter case, use-before-assign isn't UB; in the former,
5356 // we have no clue what they'll be assigned to).
5357 const auto *VD =
5358 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5359 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5360 return false;
5361
5362 const Expr *Init = VD->getAnyInitializer();
5363 if (!Init)
5364 return false;
5365
5366 const Expr *E = Init->IgnoreParens();
5367 if (!tryUnwrapAllocSizeCall(E))
5368 return false;
5369
5370 // Store E instead of E unwrapped so that the type of the LValue's base is
5371 // what the user wanted.
5372 Result.setInvalid(E);
5373
5374 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5375 Result.addUnsizedArray(Info, Pointee);
5376 return true;
5377}
5378
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005379namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005380class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005381 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005382 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005383 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005384
Peter Collingbournee9200682011-05-13 03:29:01 +00005385 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005386 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005387 return true;
5388 }
George Burgess IVe3763372016-12-22 02:50:20 +00005389
George Burgess IVf9013bf2017-02-10 22:52:29 +00005390 bool evaluateLValue(const Expr *E, LValue &Result) {
5391 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5392 }
5393
5394 bool evaluatePointer(const Expr *E, LValue &Result) {
5395 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5396 }
5397
George Burgess IVe3763372016-12-22 02:50:20 +00005398 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005399public:
Mike Stump11289f42009-09-09 15:08:12 +00005400
George Burgess IVf9013bf2017-02-10 22:52:29 +00005401 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5402 : ExprEvaluatorBaseTy(info), Result(Result),
5403 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005404
Richard Smith2e312c82012-03-03 22:46:17 +00005405 bool Success(const APValue &V, const Expr *E) {
5406 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005407 return true;
5408 }
Richard Smithfddd3842011-12-30 21:15:51 +00005409 bool ZeroInitialization(const Expr *E) {
Yaxun Liu402804b2016-12-15 08:09:08 +00005410 auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
5411 Result.set((Expr*)nullptr, 0, false, true, Offset);
5412 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005413 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005414
John McCall45d55e42010-05-07 21:00:08 +00005415 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005416 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005417 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005418 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005419 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00005420 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005421 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005422 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005423 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005424 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005425 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005426 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005427 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005428 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005429 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005430 }
Richard Smithd62306a2011-11-10 06:34:14 +00005431 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005432 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005433 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005434 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005435 if (!Info.CurrentCall->This) {
5436 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005437 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005438 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005439 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005440 return false;
5441 }
Richard Smithd62306a2011-11-10 06:34:14 +00005442 Result = *Info.CurrentCall->This;
5443 return true;
5444 }
John McCallc07a0c72011-02-17 10:25:35 +00005445
Eli Friedman449fe542009-03-23 04:56:01 +00005446 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005447};
Chris Lattner05706e882008-07-11 18:11:29 +00005448} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005449
George Burgess IVf9013bf2017-02-10 22:52:29 +00005450static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5451 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005452 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005453 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005454}
5455
John McCall45d55e42010-05-07 21:00:08 +00005456bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005457 if (E->getOpcode() != BO_Add &&
5458 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005459 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005460
Chris Lattner05706e882008-07-11 18:11:29 +00005461 const Expr *PExp = E->getLHS();
5462 const Expr *IExp = E->getRHS();
5463 if (IExp->getType()->isPointerType())
5464 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005465
George Burgess IVf9013bf2017-02-10 22:52:29 +00005466 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005467 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005468 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005469
John McCall45d55e42010-05-07 21:00:08 +00005470 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005471 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005472 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005473
Richard Smith96e0c102011-11-04 02:25:55 +00005474 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005475 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005476
Ted Kremenek28831752012-08-23 20:46:57 +00005477 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005478 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005479}
Eli Friedman9a156e52008-11-12 09:44:48 +00005480
John McCall45d55e42010-05-07 21:00:08 +00005481bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005482 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005483}
Mike Stump11289f42009-09-09 15:08:12 +00005484
Peter Collingbournee9200682011-05-13 03:29:01 +00005485bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5486 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005487
Eli Friedman847a2bc2009-12-27 05:43:15 +00005488 switch (E->getCastKind()) {
5489 default:
5490 break;
5491
John McCalle3027922010-08-25 11:45:40 +00005492 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005493 case CK_CPointerToObjCPointerCast:
5494 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005495 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005496 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005497 if (!Visit(SubExpr))
5498 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005499 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5500 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5501 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005502 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005503 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005504 if (SubExpr->getType()->isVoidPointerType())
5505 CCEDiag(E, diag::note_constexpr_invalid_cast)
5506 << 3 << SubExpr->getType();
5507 else
5508 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5509 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005510 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5511 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005512 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005513
Anders Carlsson18275092010-10-31 20:41:46 +00005514 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005515 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005516 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005517 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005518 if (!Result.Base && Result.Offset.isZero())
5519 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005520
Richard Smithd62306a2011-11-10 06:34:14 +00005521 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005522 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005523 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5524 castAs<PointerType>()->getPointeeType(),
5525 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005526
Richard Smith027bf112011-11-17 22:56:20 +00005527 case CK_BaseToDerived:
5528 if (!Visit(E->getSubExpr()))
5529 return false;
5530 if (!Result.Base && Result.Offset.isZero())
5531 return true;
5532 return HandleBaseToDerivedCast(Info, E, Result);
5533
Richard Smith0b0a0b62011-10-29 20:57:55 +00005534 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005535 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005536 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005537
John McCalle3027922010-08-25 11:45:40 +00005538 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005539 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5540
Richard Smith2e312c82012-03-03 22:46:17 +00005541 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005542 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005543 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005544
John McCall45d55e42010-05-07 21:00:08 +00005545 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005546 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5547 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005548 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005549 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005550 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005551 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005552 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005553 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005554 return true;
5555 } else {
5556 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005557 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005558 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005559 }
5560 }
John McCalle3027922010-08-25 11:45:40 +00005561 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005562 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005563 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005564 return false;
5565 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005566 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005567 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005568 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005569 return false;
5570 }
Richard Smith96e0c102011-11-04 02:25:55 +00005571 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005572 if (const ConstantArrayType *CAT
5573 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5574 Result.addArray(Info, E, CAT);
5575 else
5576 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005577 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005578
John McCalle3027922010-08-25 11:45:40 +00005579 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005580 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005581
5582 case CK_LValueToRValue: {
5583 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005584 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005585 return false;
5586
5587 APValue RVal;
5588 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5589 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5590 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005591 return InvalidBaseOK &&
5592 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005593 return Success(RVal, E);
5594 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005595 }
5596
Richard Smith11562c52011-10-28 17:51:58 +00005597 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005598}
Chris Lattner05706e882008-07-11 18:11:29 +00005599
Hal Finkel0dd05d42014-10-03 17:18:37 +00005600static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5601 // C++ [expr.alignof]p3:
5602 // When alignof is applied to a reference type, the result is the
5603 // alignment of the referenced type.
5604 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5605 T = Ref->getPointeeType();
5606
5607 // __alignof is defined to return the preferred alignment.
5608 return Info.Ctx.toCharUnitsFromBits(
5609 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5610}
5611
5612static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5613 E = E->IgnoreParens();
5614
5615 // The kinds of expressions that we have special-case logic here for
5616 // should be kept up to date with the special checks for those
5617 // expressions in Sema.
5618
5619 // alignof decl is always accepted, even if it doesn't make sense: we default
5620 // to 1 in those cases.
5621 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5622 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5623 /*RefAsPointee*/true);
5624
5625 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5626 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5627 /*RefAsPointee*/true);
5628
5629 return GetAlignOfType(Info, E->getType());
5630}
5631
George Burgess IVe3763372016-12-22 02:50:20 +00005632// To be clear: this happily visits unsupported builtins. Better name welcomed.
5633bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5634 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5635 return true;
5636
George Burgess IVf9013bf2017-02-10 22:52:29 +00005637 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005638 return false;
5639
5640 Result.setInvalid(E);
5641 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5642 Result.addUnsizedArray(Info, PointeeTy);
5643 return true;
5644}
5645
Peter Collingbournee9200682011-05-13 03:29:01 +00005646bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005647 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005648 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005649
Richard Smith6328cbd2016-11-16 00:57:23 +00005650 if (unsigned BuiltinOp = E->getBuiltinCallee())
5651 return VisitBuiltinCallExpr(E, BuiltinOp);
5652
George Burgess IVe3763372016-12-22 02:50:20 +00005653 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005654}
5655
5656bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5657 unsigned BuiltinOp) {
5658 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005659 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005660 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005661 case Builtin::BI__builtin_assume_aligned: {
5662 // We need to be very careful here because: if the pointer does not have the
5663 // asserted alignment, then the behavior is undefined, and undefined
5664 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005665 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005666 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005667
Hal Finkel0dd05d42014-10-03 17:18:37 +00005668 LValue OffsetResult(Result);
5669 APSInt Alignment;
5670 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5671 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005672 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005673
5674 if (E->getNumArgs() > 2) {
5675 APSInt Offset;
5676 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5677 return false;
5678
Richard Smith642a2362017-01-30 23:30:26 +00005679 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005680 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5681 }
5682
5683 // If there is a base object, then it must have the correct alignment.
5684 if (OffsetResult.Base) {
5685 CharUnits BaseAlignment;
5686 if (const ValueDecl *VD =
5687 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5688 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5689 } else {
5690 BaseAlignment =
5691 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5692 }
5693
5694 if (BaseAlignment < Align) {
5695 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005696 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005697 CCEDiag(E->getArg(0),
5698 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005699 << (unsigned)BaseAlignment.getQuantity()
5700 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005701 return false;
5702 }
5703 }
5704
5705 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005706 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005707 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005708
Richard Smith642a2362017-01-30 23:30:26 +00005709 (OffsetResult.Base
5710 ? CCEDiag(E->getArg(0),
5711 diag::note_constexpr_baa_insufficient_alignment) << 1
5712 : CCEDiag(E->getArg(0),
5713 diag::note_constexpr_baa_value_insufficient_alignment))
5714 << (int)OffsetResult.Offset.getQuantity()
5715 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005716 return false;
5717 }
5718
5719 return true;
5720 }
Richard Smithe9507952016-11-12 01:39:56 +00005721
5722 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005723 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005724 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005725 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005726 if (Info.getLangOpts().CPlusPlus11)
5727 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5728 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005729 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005730 else
5731 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5732 // Fall through.
5733 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005734 case Builtin::BI__builtin_wcschr:
5735 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005736 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005737 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005738 if (!Visit(E->getArg(0)))
5739 return false;
5740 APSInt Desired;
5741 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5742 return false;
5743 uint64_t MaxLength = uint64_t(-1);
5744 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005745 BuiltinOp != Builtin::BIwcschr &&
5746 BuiltinOp != Builtin::BI__builtin_strchr &&
5747 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005748 APSInt N;
5749 if (!EvaluateInteger(E->getArg(2), N, Info))
5750 return false;
5751 MaxLength = N.getExtValue();
5752 }
5753
Richard Smith8110c9d2016-11-29 19:45:17 +00005754 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005755
Richard Smith8110c9d2016-11-29 19:45:17 +00005756 // Figure out what value we're actually looking for (after converting to
5757 // the corresponding unsigned type if necessary).
5758 uint64_t DesiredVal;
5759 bool StopAtNull = false;
5760 switch (BuiltinOp) {
5761 case Builtin::BIstrchr:
5762 case Builtin::BI__builtin_strchr:
5763 // strchr compares directly to the passed integer, and therefore
5764 // always fails if given an int that is not a char.
5765 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5766 E->getArg(1)->getType(),
5767 Desired),
5768 Desired))
5769 return ZeroInitialization(E);
5770 StopAtNull = true;
5771 // Fall through.
5772 case Builtin::BImemchr:
5773 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005774 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005775 // memchr compares by converting both sides to unsigned char. That's also
5776 // correct for strchr if we get this far (to cope with plain char being
5777 // unsigned in the strchr case).
5778 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5779 break;
Richard Smithe9507952016-11-12 01:39:56 +00005780
Richard Smith8110c9d2016-11-29 19:45:17 +00005781 case Builtin::BIwcschr:
5782 case Builtin::BI__builtin_wcschr:
5783 StopAtNull = true;
5784 // Fall through.
5785 case Builtin::BIwmemchr:
5786 case Builtin::BI__builtin_wmemchr:
5787 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5788 DesiredVal = Desired.getZExtValue();
5789 break;
5790 }
Richard Smithe9507952016-11-12 01:39:56 +00005791
5792 for (; MaxLength; --MaxLength) {
5793 APValue Char;
5794 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5795 !Char.isInt())
5796 return false;
5797 if (Char.getInt().getZExtValue() == DesiredVal)
5798 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005799 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005800 break;
5801 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5802 return false;
5803 }
5804 // Not found: return nullptr.
5805 return ZeroInitialization(E);
5806 }
5807
Richard Smith6cbd65d2013-07-11 02:27:57 +00005808 default:
George Burgess IVe3763372016-12-22 02:50:20 +00005809 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005810 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005811}
Chris Lattner05706e882008-07-11 18:11:29 +00005812
5813//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005814// Member Pointer Evaluation
5815//===----------------------------------------------------------------------===//
5816
5817namespace {
5818class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005819 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005820 MemberPtr &Result;
5821
5822 bool Success(const ValueDecl *D) {
5823 Result = MemberPtr(D);
5824 return true;
5825 }
5826public:
5827
5828 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5829 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5830
Richard Smith2e312c82012-03-03 22:46:17 +00005831 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005832 Result.setFrom(V);
5833 return true;
5834 }
Richard Smithfddd3842011-12-30 21:15:51 +00005835 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005836 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005837 }
5838
5839 bool VisitCastExpr(const CastExpr *E);
5840 bool VisitUnaryAddrOf(const UnaryOperator *E);
5841};
5842} // end anonymous namespace
5843
5844static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5845 EvalInfo &Info) {
5846 assert(E->isRValue() && E->getType()->isMemberPointerType());
5847 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5848}
5849
5850bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5851 switch (E->getCastKind()) {
5852 default:
5853 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5854
5855 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005856 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005857 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005858
5859 case CK_BaseToDerivedMemberPointer: {
5860 if (!Visit(E->getSubExpr()))
5861 return false;
5862 if (E->path_empty())
5863 return true;
5864 // Base-to-derived member pointer casts store the path in derived-to-base
5865 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5866 // the wrong end of the derived->base arc, so stagger the path by one class.
5867 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5868 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5869 PathI != PathE; ++PathI) {
5870 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5871 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5872 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005873 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005874 }
5875 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5876 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005877 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005878 return true;
5879 }
5880
5881 case CK_DerivedToBaseMemberPointer:
5882 if (!Visit(E->getSubExpr()))
5883 return false;
5884 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5885 PathE = E->path_end(); PathI != PathE; ++PathI) {
5886 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5887 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5888 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005889 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005890 }
5891 return true;
5892 }
5893}
5894
5895bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5896 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5897 // member can be formed.
5898 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5899}
5900
5901//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005902// Record Evaluation
5903//===----------------------------------------------------------------------===//
5904
5905namespace {
5906 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005907 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005908 const LValue &This;
5909 APValue &Result;
5910 public:
5911
5912 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5913 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5914
Richard Smith2e312c82012-03-03 22:46:17 +00005915 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005916 Result = V;
5917 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005918 }
Richard Smithb8348f52016-05-12 22:16:28 +00005919 bool ZeroInitialization(const Expr *E) {
5920 return ZeroInitialization(E, E->getType());
5921 }
5922 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005923
Richard Smith52a980a2015-08-28 02:43:42 +00005924 bool VisitCallExpr(const CallExpr *E) {
5925 return handleCallExpr(E, Result, &This);
5926 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005927 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005928 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005929 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5930 return VisitCXXConstructExpr(E, E->getType());
5931 }
Faisal Valic72a08c2017-01-09 03:02:53 +00005932 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00005933 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005934 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005935 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005936 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005937}
Richard Smithd62306a2011-11-10 06:34:14 +00005938
Richard Smithfddd3842011-12-30 21:15:51 +00005939/// Perform zero-initialization on an object of non-union class type.
5940/// C++11 [dcl.init]p5:
5941/// To zero-initialize an object or reference of type T means:
5942/// [...]
5943/// -- if T is a (possibly cv-qualified) non-union class type,
5944/// each non-static data member and each base-class subobject is
5945/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005946static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5947 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005948 const LValue &This, APValue &Result) {
5949 assert(!RD->isUnion() && "Expected non-union class type");
5950 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5951 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005952 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005953
John McCalld7bca762012-05-01 00:38:49 +00005954 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005955 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5956
5957 if (CD) {
5958 unsigned Index = 0;
5959 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005960 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005961 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5962 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005963 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5964 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005965 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005966 Result.getStructBase(Index)))
5967 return false;
5968 }
5969 }
5970
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005971 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005972 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005973 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005974 continue;
5975
5976 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005977 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005978 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005979
David Blaikie2d7c57e2012-04-30 02:36:29 +00005980 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005981 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005982 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005983 return false;
5984 }
5985
5986 return true;
5987}
5988
Richard Smithb8348f52016-05-12 22:16:28 +00005989bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5990 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005991 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005992 if (RD->isUnion()) {
5993 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5994 // object's first non-static named data member is zero-initialized
5995 RecordDecl::field_iterator I = RD->field_begin();
5996 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005997 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005998 return true;
5999 }
6000
6001 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006002 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006003 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006004 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006005 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006006 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006007 }
6008
Richard Smith5d108602012-02-17 00:44:16 +00006009 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006010 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006011 return false;
6012 }
6013
Richard Smitha8105bc2012-01-06 16:39:00 +00006014 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006015}
6016
Richard Smithe97cbd72011-11-11 04:05:33 +00006017bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6018 switch (E->getCastKind()) {
6019 default:
6020 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6021
6022 case CK_ConstructorConversion:
6023 return Visit(E->getSubExpr());
6024
6025 case CK_DerivedToBase:
6026 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006027 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006028 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006029 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006030 if (!DerivedObject.isStruct())
6031 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006032
6033 // Derived-to-base rvalue conversion: just slice off the derived part.
6034 APValue *Value = &DerivedObject;
6035 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6036 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6037 PathE = E->path_end(); PathI != PathE; ++PathI) {
6038 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6039 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6040 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6041 RD = Base;
6042 }
6043 Result = *Value;
6044 return true;
6045 }
6046 }
6047}
6048
Richard Smithd62306a2011-11-10 06:34:14 +00006049bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006050 if (E->isTransparent())
6051 return Visit(E->getInit(0));
6052
Richard Smithd62306a2011-11-10 06:34:14 +00006053 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006054 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006055 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6056
6057 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006058 const FieldDecl *Field = E->getInitializedFieldInUnion();
6059 Result = APValue(Field);
6060 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006061 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006062
6063 // If the initializer list for a union does not contain any elements, the
6064 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006065 // FIXME: The element should be initialized from an initializer list.
6066 // Is this difference ever observable for initializer lists which
6067 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006068 ImplicitValueInitExpr VIE(Field->getType());
6069 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6070
Richard Smithd62306a2011-11-10 06:34:14 +00006071 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006072 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6073 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006074
6075 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6076 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6077 isa<CXXDefaultInitExpr>(InitExpr));
6078
Richard Smithb228a862012-02-15 02:18:13 +00006079 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006080 }
6081
Richard Smith872307e2016-03-08 22:17:41 +00006082 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006083 if (Result.isUninit())
6084 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6085 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006086 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006087 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006088
6089 // Initialize base classes.
6090 if (CXXRD) {
6091 for (const auto &Base : CXXRD->bases()) {
6092 assert(ElementNo < E->getNumInits() && "missing init for base class");
6093 const Expr *Init = E->getInit(ElementNo);
6094
6095 LValue Subobject = This;
6096 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6097 return false;
6098
6099 APValue &FieldVal = Result.getStructBase(ElementNo);
6100 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006101 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006102 return false;
6103 Success = false;
6104 }
6105 ++ElementNo;
6106 }
6107 }
6108
6109 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006110 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006111 // Anonymous bit-fields are not considered members of the class for
6112 // purposes of aggregate initialization.
6113 if (Field->isUnnamedBitfield())
6114 continue;
6115
6116 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006117
Richard Smith253c2a32012-01-27 01:14:48 +00006118 bool HaveInit = ElementNo < E->getNumInits();
6119
6120 // FIXME: Diagnostics here should point to the end of the initializer
6121 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006122 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006123 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006124 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006125
6126 // Perform an implicit value-initialization for members beyond the end of
6127 // the initializer list.
6128 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006129 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006130
Richard Smith852c9db2013-04-20 22:23:05 +00006131 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6132 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6133 isa<CXXDefaultInitExpr>(Init));
6134
Richard Smith49ca8aa2013-08-06 07:09:20 +00006135 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6136 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6137 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006138 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006139 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006140 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006141 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006142 }
6143 }
6144
Richard Smith253c2a32012-01-27 01:14:48 +00006145 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006146}
6147
Richard Smithb8348f52016-05-12 22:16:28 +00006148bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6149 QualType T) {
6150 // Note that E's type is not necessarily the type of our class here; we might
6151 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006152 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006153 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6154
Richard Smithfddd3842011-12-30 21:15:51 +00006155 bool ZeroInit = E->requiresZeroInitialization();
6156 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006157 // If we've already performed zero-initialization, we're already done.
6158 if (!Result.isUninit())
6159 return true;
6160
Richard Smithda3f4fd2014-03-05 23:32:50 +00006161 // We can get here in two different ways:
6162 // 1) We're performing value-initialization, and should zero-initialize
6163 // the object, or
6164 // 2) We're performing default-initialization of an object with a trivial
6165 // constexpr default constructor, in which case we should start the
6166 // lifetimes of all the base subobjects (there can be no data member
6167 // subobjects in this case) per [basic.life]p1.
6168 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006169 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006170 }
6171
Craig Topper36250ad2014-05-12 05:36:57 +00006172 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006173 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006174
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006175 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006176 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006177
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006178 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006179 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006180 if (const MaterializeTemporaryExpr *ME
6181 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6182 return Visit(ME->GetTemporaryExpr());
6183
Richard Smithb8348f52016-05-12 22:16:28 +00006184 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006185 return false;
6186
Craig Topper5fc8fc22014-08-27 06:28:36 +00006187 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006188 return HandleConstructorCall(E, This, Args,
6189 cast<CXXConstructorDecl>(Definition), Info,
6190 Result);
6191}
6192
6193bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6194 const CXXInheritedCtorInitExpr *E) {
6195 if (!Info.CurrentCall) {
6196 assert(Info.checkingPotentialConstantExpression());
6197 return false;
6198 }
6199
6200 const CXXConstructorDecl *FD = E->getConstructor();
6201 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6202 return false;
6203
6204 const FunctionDecl *Definition = nullptr;
6205 auto Body = FD->getBody(Definition);
6206
6207 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6208 return false;
6209
6210 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006211 cast<CXXConstructorDecl>(Definition), Info,
6212 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006213}
6214
Richard Smithcc1b96d2013-06-12 22:31:48 +00006215bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6216 const CXXStdInitializerListExpr *E) {
6217 const ConstantArrayType *ArrayType =
6218 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6219
6220 LValue Array;
6221 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6222 return false;
6223
6224 // Get a pointer to the first element of the array.
6225 Array.addArray(Info, E, ArrayType);
6226
6227 // FIXME: Perform the checks on the field types in SemaInit.
6228 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6229 RecordDecl::field_iterator Field = Record->field_begin();
6230 if (Field == Record->field_end())
6231 return Error(E);
6232
6233 // Start pointer.
6234 if (!Field->getType()->isPointerType() ||
6235 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6236 ArrayType->getElementType()))
6237 return Error(E);
6238
6239 // FIXME: What if the initializer_list type has base classes, etc?
6240 Result = APValue(APValue::UninitStruct(), 0, 2);
6241 Array.moveInto(Result.getStructField(0));
6242
6243 if (++Field == Record->field_end())
6244 return Error(E);
6245
6246 if (Field->getType()->isPointerType() &&
6247 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6248 ArrayType->getElementType())) {
6249 // End pointer.
6250 if (!HandleLValueArrayAdjustment(Info, E, Array,
6251 ArrayType->getElementType(),
6252 ArrayType->getSize().getZExtValue()))
6253 return false;
6254 Array.moveInto(Result.getStructField(1));
6255 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6256 // Length.
6257 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6258 else
6259 return Error(E);
6260
6261 if (++Field != Record->field_end())
6262 return Error(E);
6263
6264 return true;
6265}
6266
Faisal Valic72a08c2017-01-09 03:02:53 +00006267bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6268 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6269 if (ClosureClass->isInvalidDecl()) return false;
6270
6271 if (Info.checkingPotentialConstantExpression()) return true;
6272 if (E->capture_size()) {
6273 Info.FFDiag(E, diag::note_unimplemented_constexpr_lambda_feature_ast)
6274 << "can not evaluate lambda expressions with captures";
6275 return false;
6276 }
6277 // FIXME: Implement captures.
6278 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, /*NumFields*/0);
6279 return true;
6280}
6281
Richard Smithd62306a2011-11-10 06:34:14 +00006282static bool EvaluateRecord(const Expr *E, const LValue &This,
6283 APValue &Result, EvalInfo &Info) {
6284 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006285 "can't evaluate expression as a record rvalue");
6286 return RecordExprEvaluator(Info, This, Result).Visit(E);
6287}
6288
6289//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006290// Temporary Evaluation
6291//
6292// Temporaries are represented in the AST as rvalues, but generally behave like
6293// lvalues. The full-object of which the temporary is a subobject is implicitly
6294// materialized so that a reference can bind to it.
6295//===----------------------------------------------------------------------===//
6296namespace {
6297class TemporaryExprEvaluator
6298 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6299public:
6300 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006301 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006302
6303 /// Visit an expression which constructs the value of this temporary.
6304 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006305 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006306 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6307 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006308 }
6309
6310 bool VisitCastExpr(const CastExpr *E) {
6311 switch (E->getCastKind()) {
6312 default:
6313 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6314
6315 case CK_ConstructorConversion:
6316 return VisitConstructExpr(E->getSubExpr());
6317 }
6318 }
6319 bool VisitInitListExpr(const InitListExpr *E) {
6320 return VisitConstructExpr(E);
6321 }
6322 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6323 return VisitConstructExpr(E);
6324 }
6325 bool VisitCallExpr(const CallExpr *E) {
6326 return VisitConstructExpr(E);
6327 }
Richard Smith513955c2014-12-17 19:24:30 +00006328 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6329 return VisitConstructExpr(E);
6330 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006331 bool VisitLambdaExpr(const LambdaExpr *E) {
6332 return VisitConstructExpr(E);
6333 }
Richard Smith027bf112011-11-17 22:56:20 +00006334};
6335} // end anonymous namespace
6336
6337/// Evaluate an expression of record type as a temporary.
6338static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006339 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006340 return TemporaryExprEvaluator(Info, Result).Visit(E);
6341}
6342
6343//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006344// Vector Evaluation
6345//===----------------------------------------------------------------------===//
6346
6347namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006348 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006349 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006350 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006351 public:
Mike Stump11289f42009-09-09 15:08:12 +00006352
Richard Smith2d406342011-10-22 21:10:00 +00006353 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6354 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006355
Craig Topper9798b932015-09-29 04:30:05 +00006356 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006357 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6358 // FIXME: remove this APValue copy.
6359 Result = APValue(V.data(), V.size());
6360 return true;
6361 }
Richard Smith2e312c82012-03-03 22:46:17 +00006362 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006363 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006364 Result = V;
6365 return true;
6366 }
Richard Smithfddd3842011-12-30 21:15:51 +00006367 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006368
Richard Smith2d406342011-10-22 21:10:00 +00006369 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006370 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006371 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006372 bool VisitInitListExpr(const InitListExpr *E);
6373 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006374 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006375 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006376 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006377 };
6378} // end anonymous namespace
6379
6380static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006381 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006382 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006383}
6384
George Burgess IV533ff002015-12-11 00:23:35 +00006385bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006386 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006387 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006388
Richard Smith161f09a2011-12-06 22:44:34 +00006389 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006390 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006391
Eli Friedmanc757de22011-03-25 00:43:55 +00006392 switch (E->getCastKind()) {
6393 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006394 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006395 if (SETy->isIntegerType()) {
6396 APSInt IntResult;
6397 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006398 return false;
6399 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006400 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006401 APFloat FloatResult(0.0);
6402 if (!EvaluateFloat(SE, FloatResult, Info))
6403 return false;
6404 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006405 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006406 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006407 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006408
6409 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006410 SmallVector<APValue, 4> Elts(NElts, Val);
6411 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006412 }
Eli Friedman803acb32011-12-22 03:51:45 +00006413 case CK_BitCast: {
6414 // Evaluate the operand into an APInt we can extract from.
6415 llvm::APInt SValInt;
6416 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6417 return false;
6418 // Extract the elements
6419 QualType EltTy = VTy->getElementType();
6420 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6421 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6422 SmallVector<APValue, 4> Elts;
6423 if (EltTy->isRealFloatingType()) {
6424 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006425 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006426 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006427 FloatEltSize = 80;
6428 for (unsigned i = 0; i < NElts; i++) {
6429 llvm::APInt Elt;
6430 if (BigEndian)
6431 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6432 else
6433 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006434 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006435 }
6436 } else if (EltTy->isIntegerType()) {
6437 for (unsigned i = 0; i < NElts; i++) {
6438 llvm::APInt Elt;
6439 if (BigEndian)
6440 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6441 else
6442 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6443 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6444 }
6445 } else {
6446 return Error(E);
6447 }
6448 return Success(Elts, E);
6449 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006450 default:
Richard Smith11562c52011-10-28 17:51:58 +00006451 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006452 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006453}
6454
Richard Smith2d406342011-10-22 21:10:00 +00006455bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006456VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006457 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006458 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006459 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006460
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006461 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006462 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006463
Eli Friedmanb9c71292012-01-03 23:24:20 +00006464 // The number of initializers can be less than the number of
6465 // vector elements. For OpenCL, this can be due to nested vector
6466 // initialization. For GCC compatibility, missing trailing elements
6467 // should be initialized with zeroes.
6468 unsigned CountInits = 0, CountElts = 0;
6469 while (CountElts < NumElements) {
6470 // Handle nested vector initialization.
6471 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006472 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006473 APValue v;
6474 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6475 return Error(E);
6476 unsigned vlen = v.getVectorLength();
6477 for (unsigned j = 0; j < vlen; j++)
6478 Elements.push_back(v.getVectorElt(j));
6479 CountElts += vlen;
6480 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006481 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006482 if (CountInits < NumInits) {
6483 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006484 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006485 } else // trailing integer zero.
6486 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6487 Elements.push_back(APValue(sInt));
6488 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006489 } else {
6490 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006491 if (CountInits < NumInits) {
6492 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006493 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006494 } else // trailing float zero.
6495 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6496 Elements.push_back(APValue(f));
6497 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006498 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006499 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006500 }
Richard Smith2d406342011-10-22 21:10:00 +00006501 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006502}
6503
Richard Smith2d406342011-10-22 21:10:00 +00006504bool
Richard Smithfddd3842011-12-30 21:15:51 +00006505VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006506 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006507 QualType EltTy = VT->getElementType();
6508 APValue ZeroElement;
6509 if (EltTy->isIntegerType())
6510 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6511 else
6512 ZeroElement =
6513 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6514
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006515 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006516 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006517}
6518
Richard Smith2d406342011-10-22 21:10:00 +00006519bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006520 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006521 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006522}
6523
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006524//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006525// Array Evaluation
6526//===----------------------------------------------------------------------===//
6527
6528namespace {
6529 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006530 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006531 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006532 APValue &Result;
6533 public:
6534
Richard Smithd62306a2011-11-10 06:34:14 +00006535 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6536 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006537
6538 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006539 assert((V.isArray() || V.isLValue()) &&
6540 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006541 Result = V;
6542 return true;
6543 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006544
Richard Smithfddd3842011-12-30 21:15:51 +00006545 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006546 const ConstantArrayType *CAT =
6547 Info.Ctx.getAsConstantArrayType(E->getType());
6548 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006549 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006550
6551 Result = APValue(APValue::UninitArray(), 0,
6552 CAT->getSize().getZExtValue());
6553 if (!Result.hasArrayFiller()) return true;
6554
Richard Smithfddd3842011-12-30 21:15:51 +00006555 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006556 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006557 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006558 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006559 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006560 }
6561
Richard Smith52a980a2015-08-28 02:43:42 +00006562 bool VisitCallExpr(const CallExpr *E) {
6563 return handleCallExpr(E, Result, &This);
6564 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006565 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006566 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006567 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006568 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6569 const LValue &Subobject,
6570 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006571 };
6572} // end anonymous namespace
6573
Richard Smithd62306a2011-11-10 06:34:14 +00006574static bool EvaluateArray(const Expr *E, const LValue &This,
6575 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006576 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006577 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006578}
6579
6580bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6581 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6582 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006583 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006584
Richard Smithca2cfbf2011-12-22 01:07:19 +00006585 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6586 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006587 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006588 LValue LV;
6589 if (!EvaluateLValue(E->getInit(0), LV, Info))
6590 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006591 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006592 LV.moveInto(Val);
6593 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006594 }
6595
Richard Smith253c2a32012-01-27 01:14:48 +00006596 bool Success = true;
6597
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006598 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6599 "zero-initialized array shouldn't have any initialized elts");
6600 APValue Filler;
6601 if (Result.isArray() && Result.hasArrayFiller())
6602 Filler = Result.getArrayFiller();
6603
Richard Smith9543c5e2013-04-22 14:44:29 +00006604 unsigned NumEltsToInit = E->getNumInits();
6605 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006606 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006607
6608 // If the initializer might depend on the array index, run it for each
6609 // array element. For now, just whitelist non-class value-initialization.
6610 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6611 NumEltsToInit = NumElts;
6612
6613 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006614
6615 // If the array was previously zero-initialized, preserve the
6616 // zero-initialized values.
6617 if (!Filler.isUninit()) {
6618 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6619 Result.getArrayInitializedElt(I) = Filler;
6620 if (Result.hasArrayFiller())
6621 Result.getArrayFiller() = Filler;
6622 }
6623
Richard Smithd62306a2011-11-10 06:34:14 +00006624 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006625 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006626 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6627 const Expr *Init =
6628 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006629 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006630 Info, Subobject, Init) ||
6631 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006632 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006633 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006634 return false;
6635 Success = false;
6636 }
Richard Smithd62306a2011-11-10 06:34:14 +00006637 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006638
Richard Smith9543c5e2013-04-22 14:44:29 +00006639 if (!Result.hasArrayFiller())
6640 return Success;
6641
6642 // If we get here, we have a trivial filler, which we can just evaluate
6643 // once and splat over the rest of the array elements.
6644 assert(FillerExpr && "no array filler for incomplete init list");
6645 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6646 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006647}
6648
Richard Smith410306b2016-12-12 02:53:20 +00006649bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6650 if (E->getCommonExpr() &&
6651 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6652 Info, E->getCommonExpr()->getSourceExpr()))
6653 return false;
6654
6655 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6656
6657 uint64_t Elements = CAT->getSize().getZExtValue();
6658 Result = APValue(APValue::UninitArray(), Elements, Elements);
6659
6660 LValue Subobject = This;
6661 Subobject.addArray(Info, E, CAT);
6662
6663 bool Success = true;
6664 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6665 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6666 Info, Subobject, E->getSubExpr()) ||
6667 !HandleLValueArrayAdjustment(Info, E, Subobject,
6668 CAT->getElementType(), 1)) {
6669 if (!Info.noteFailure())
6670 return false;
6671 Success = false;
6672 }
6673 }
6674
6675 return Success;
6676}
6677
Richard Smith027bf112011-11-17 22:56:20 +00006678bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006679 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6680}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006681
Richard Smith9543c5e2013-04-22 14:44:29 +00006682bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6683 const LValue &Subobject,
6684 APValue *Value,
6685 QualType Type) {
6686 bool HadZeroInit = !Value->isUninit();
6687
6688 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6689 unsigned N = CAT->getSize().getZExtValue();
6690
6691 // Preserve the array filler if we had prior zero-initialization.
6692 APValue Filler =
6693 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6694 : APValue();
6695
6696 *Value = APValue(APValue::UninitArray(), N, N);
6697
6698 if (HadZeroInit)
6699 for (unsigned I = 0; I != N; ++I)
6700 Value->getArrayInitializedElt(I) = Filler;
6701
6702 // Initialize the elements.
6703 LValue ArrayElt = Subobject;
6704 ArrayElt.addArray(Info, E, CAT);
6705 for (unsigned I = 0; I != N; ++I)
6706 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6707 CAT->getElementType()) ||
6708 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6709 CAT->getElementType(), 1))
6710 return false;
6711
6712 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006713 }
Richard Smith027bf112011-11-17 22:56:20 +00006714
Richard Smith9543c5e2013-04-22 14:44:29 +00006715 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006716 return Error(E);
6717
Richard Smithb8348f52016-05-12 22:16:28 +00006718 return RecordExprEvaluator(Info, Subobject, *Value)
6719 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006720}
6721
Richard Smithf3e9e432011-11-07 09:22:26 +00006722//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006723// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006724//
6725// As a GNU extension, we support casting pointers to sufficiently-wide integer
6726// types and back in constant folding. Integer values are thus represented
6727// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006728//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006729
6730namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006731class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006732 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006733 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006734public:
Richard Smith2e312c82012-03-03 22:46:17 +00006735 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006736 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006737
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006738 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006739 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006740 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006741 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006742 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006743 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006744 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006745 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006746 return true;
6747 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006748 bool Success(const llvm::APSInt &SI, const Expr *E) {
6749 return Success(SI, E, Result);
6750 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006751
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006752 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006753 assert(E->getType()->isIntegralOrEnumerationType() &&
6754 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006755 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006756 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006757 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006758 Result.getInt().setIsUnsigned(
6759 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006760 return true;
6761 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006762 bool Success(const llvm::APInt &I, const Expr *E) {
6763 return Success(I, E, Result);
6764 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006765
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006766 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006767 assert(E->getType()->isIntegralOrEnumerationType() &&
6768 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006769 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006770 return true;
6771 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006772 bool Success(uint64_t Value, const Expr *E) {
6773 return Success(Value, E, Result);
6774 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006775
Ken Dyckdbc01912011-03-11 02:13:43 +00006776 bool Success(CharUnits Size, const Expr *E) {
6777 return Success(Size.getQuantity(), E);
6778 }
6779
Richard Smith2e312c82012-03-03 22:46:17 +00006780 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006781 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006782 Result = V;
6783 return true;
6784 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006785 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006786 }
Mike Stump11289f42009-09-09 15:08:12 +00006787
Richard Smithfddd3842011-12-30 21:15:51 +00006788 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006789
Peter Collingbournee9200682011-05-13 03:29:01 +00006790 //===--------------------------------------------------------------------===//
6791 // Visitor Methods
6792 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006793
Chris Lattner7174bf32008-07-12 00:38:25 +00006794 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006795 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006796 }
6797 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006798 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006799 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006800
6801 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6802 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006803 if (CheckReferencedDecl(E, E->getDecl()))
6804 return true;
6805
6806 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006807 }
6808 bool VisitMemberExpr(const MemberExpr *E) {
6809 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006810 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006811 return true;
6812 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006813
6814 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006815 }
6816
Peter Collingbournee9200682011-05-13 03:29:01 +00006817 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006818 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006819 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006820 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006821 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006822
Peter Collingbournee9200682011-05-13 03:29:01 +00006823 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006824 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006825
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006826 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006827 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006828 }
Mike Stump11289f42009-09-09 15:08:12 +00006829
Ted Kremeneke65b0862012-03-06 20:05:56 +00006830 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6831 return Success(E->getValue(), E);
6832 }
Richard Smith410306b2016-12-12 02:53:20 +00006833
6834 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6835 if (Info.ArrayInitIndex == uint64_t(-1)) {
6836 // We were asked to evaluate this subexpression independent of the
6837 // enclosing ArrayInitLoopExpr. We can't do that.
6838 Info.FFDiag(E);
6839 return false;
6840 }
6841 return Success(Info.ArrayInitIndex, E);
6842 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00006843
Richard Smith4ce706a2011-10-11 21:43:33 +00006844 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006845 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006846 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006847 }
6848
Douglas Gregor29c42f22012-02-24 07:38:34 +00006849 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6850 return Success(E->getValue(), E);
6851 }
6852
John Wiegley6242b6a2011-04-28 00:16:57 +00006853 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6854 return Success(E->getValue(), E);
6855 }
6856
John Wiegleyf9f65842011-04-25 06:54:41 +00006857 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6858 return Success(E->getValue(), E);
6859 }
6860
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006861 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006862 bool VisitUnaryImag(const UnaryOperator *E);
6863
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006864 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006865 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006866
Eli Friedman4e7a2412009-02-27 04:45:43 +00006867 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006868};
Chris Lattner05706e882008-07-11 18:11:29 +00006869} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006870
Richard Smith11562c52011-10-28 17:51:58 +00006871/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6872/// produce either the integer value or a pointer.
6873///
6874/// GCC has a heinous extension which folds casts between pointer types and
6875/// pointer-sized integral types. We support this by allowing the evaluation of
6876/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6877/// Some simple arithmetic on such values is supported (they are treated much
6878/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006879static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006880 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006881 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006882 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006883}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006884
Richard Smithf57d8cb2011-12-09 22:58:01 +00006885static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006886 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006887 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006888 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006889 if (!Val.isInt()) {
6890 // FIXME: It would be better to produce the diagnostic for casting
6891 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00006892 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006893 return false;
6894 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006895 Result = Val.getInt();
6896 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006897}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006898
Richard Smithf57d8cb2011-12-09 22:58:01 +00006899/// Check whether the given declaration can be directly converted to an integral
6900/// rvalue. If not, no diagnostic is produced; there are other things we can
6901/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006902bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006903 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006904 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006905 // Check for signedness/width mismatches between E type and ECD value.
6906 bool SameSign = (ECD->getInitVal().isSigned()
6907 == E->getType()->isSignedIntegerOrEnumerationType());
6908 bool SameWidth = (ECD->getInitVal().getBitWidth()
6909 == Info.Ctx.getIntWidth(E->getType()));
6910 if (SameSign && SameWidth)
6911 return Success(ECD->getInitVal(), E);
6912 else {
6913 // Get rid of mismatch (otherwise Success assertions will fail)
6914 // by computing a new value matching the type of E.
6915 llvm::APSInt Val = ECD->getInitVal();
6916 if (!SameSign)
6917 Val.setIsSigned(!ECD->getInitVal().isSigned());
6918 if (!SameWidth)
6919 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6920 return Success(Val, E);
6921 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006922 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006923 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006924}
6925
Chris Lattner86ee2862008-10-06 06:40:35 +00006926/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6927/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006928static int EvaluateBuiltinClassifyType(const CallExpr *E,
6929 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006930 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006931 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006932 enum gcc_type_class {
6933 no_type_class = -1,
6934 void_type_class, integer_type_class, char_type_class,
6935 enumeral_type_class, boolean_type_class,
6936 pointer_type_class, reference_type_class, offset_type_class,
6937 real_type_class, complex_type_class,
6938 function_type_class, method_type_class,
6939 record_type_class, union_type_class,
6940 array_type_class, string_type_class,
6941 lang_type_class
6942 };
Mike Stump11289f42009-09-09 15:08:12 +00006943
6944 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006945 // ideal, however it is what gcc does.
6946 if (E->getNumArgs() == 0)
6947 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006948
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006949 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6950 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6951
6952 switch (CanTy->getTypeClass()) {
6953#define TYPE(ID, BASE)
6954#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6955#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6956#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6957#include "clang/AST/TypeNodes.def"
6958 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6959
6960 case Type::Builtin:
6961 switch (BT->getKind()) {
6962#define BUILTIN_TYPE(ID, SINGLETON_ID)
6963#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6964#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6965#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6966#include "clang/AST/BuiltinTypes.def"
6967 case BuiltinType::Void:
6968 return void_type_class;
6969
6970 case BuiltinType::Bool:
6971 return boolean_type_class;
6972
6973 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6974 case BuiltinType::UChar:
6975 case BuiltinType::UShort:
6976 case BuiltinType::UInt:
6977 case BuiltinType::ULong:
6978 case BuiltinType::ULongLong:
6979 case BuiltinType::UInt128:
6980 return integer_type_class;
6981
6982 case BuiltinType::NullPtr:
6983 return pointer_type_class;
6984
6985 case BuiltinType::WChar_U:
6986 case BuiltinType::Char16:
6987 case BuiltinType::Char32:
6988 case BuiltinType::ObjCId:
6989 case BuiltinType::ObjCClass:
6990 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00006991#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6992 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006993#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006994 case BuiltinType::OCLSampler:
6995 case BuiltinType::OCLEvent:
6996 case BuiltinType::OCLClkEvent:
6997 case BuiltinType::OCLQueue:
6998 case BuiltinType::OCLNDRange:
6999 case BuiltinType::OCLReserveID:
7000 case BuiltinType::Dependent:
7001 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7002 };
7003
7004 case Type::Enum:
7005 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7006 break;
7007
7008 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007009 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007010 break;
7011
7012 case Type::MemberPointer:
7013 if (CanTy->isMemberDataPointerType())
7014 return offset_type_class;
7015 else {
7016 // We expect member pointers to be either data or function pointers,
7017 // nothing else.
7018 assert(CanTy->isMemberFunctionPointerType());
7019 return method_type_class;
7020 }
7021
7022 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007023 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007024
7025 case Type::FunctionNoProto:
7026 case Type::FunctionProto:
7027 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7028
7029 case Type::Record:
7030 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7031 switch (RT->getDecl()->getTagKind()) {
7032 case TagTypeKind::TTK_Struct:
7033 case TagTypeKind::TTK_Class:
7034 case TagTypeKind::TTK_Interface:
7035 return record_type_class;
7036
7037 case TagTypeKind::TTK_Enum:
7038 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7039
7040 case TagTypeKind::TTK_Union:
7041 return union_type_class;
7042 }
7043 }
David Blaikie83d382b2011-09-23 05:06:16 +00007044 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007045
7046 case Type::ConstantArray:
7047 case Type::VariableArray:
7048 case Type::IncompleteArray:
7049 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7050
7051 case Type::BlockPointer:
7052 case Type::LValueReference:
7053 case Type::RValueReference:
7054 case Type::Vector:
7055 case Type::ExtVector:
7056 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007057 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007058 case Type::ObjCObject:
7059 case Type::ObjCInterface:
7060 case Type::ObjCObjectPointer:
7061 case Type::Pipe:
7062 case Type::Atomic:
7063 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7064 }
7065
7066 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007067}
7068
Richard Smith5fab0c92011-12-28 19:48:30 +00007069/// EvaluateBuiltinConstantPForLValue - Determine the result of
7070/// __builtin_constant_p when applied to the given lvalue.
7071///
7072/// An lvalue is only "constant" if it is a pointer or reference to the first
7073/// character of a string literal.
7074template<typename LValue>
7075static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007076 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007077 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7078}
7079
7080/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7081/// GCC as we can manage.
7082static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7083 QualType ArgType = Arg->getType();
7084
7085 // __builtin_constant_p always has one operand. The rules which gcc follows
7086 // are not precisely documented, but are as follows:
7087 //
7088 // - If the operand is of integral, floating, complex or enumeration type,
7089 // and can be folded to a known value of that type, it returns 1.
7090 // - If the operand and can be folded to a pointer to the first character
7091 // of a string literal (or such a pointer cast to an integral type), it
7092 // returns 1.
7093 //
7094 // Otherwise, it returns 0.
7095 //
7096 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7097 // its support for this does not currently work.
7098 if (ArgType->isIntegralOrEnumerationType()) {
7099 Expr::EvalResult Result;
7100 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7101 return false;
7102
7103 APValue &V = Result.Val;
7104 if (V.getKind() == APValue::Int)
7105 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007106 if (V.getKind() == APValue::LValue)
7107 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007108 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7109 return Arg->isEvaluatable(Ctx);
7110 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7111 LValue LV;
7112 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007113 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007114 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7115 : EvaluatePointer(Arg, LV, Info)) &&
7116 !Status.HasSideEffects)
7117 return EvaluateBuiltinConstantPForLValue(LV);
7118 }
7119
7120 // Anything else isn't considered to be sufficiently constant.
7121 return false;
7122}
7123
John McCall95007602010-05-10 23:27:23 +00007124/// Retrieves the "underlying object type" of the given expression,
7125/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007126static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007127 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7128 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007129 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007130 } else if (const Expr *E = B.get<const Expr*>()) {
7131 if (isa<CompoundLiteralExpr>(E))
7132 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007133 }
7134
7135 return QualType();
7136}
7137
George Burgess IV3a03fab2015-09-04 21:28:13 +00007138/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007139/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007140/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007141/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7142///
7143/// Always returns an RValue with a pointer representation.
7144static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7145 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7146
7147 auto *NoParens = E->IgnoreParens();
7148 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007149 if (Cast == nullptr)
7150 return NoParens;
7151
7152 // We only conservatively allow a few kinds of casts, because this code is
7153 // inherently a simple solution that seeks to support the common case.
7154 auto CastKind = Cast->getCastKind();
7155 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7156 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007157 return NoParens;
7158
7159 auto *SubExpr = Cast->getSubExpr();
7160 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7161 return NoParens;
7162 return ignorePointerCastsAndParens(SubExpr);
7163}
7164
George Burgess IVa51c4072015-10-16 01:49:01 +00007165/// Checks to see if the given LValue's Designator is at the end of the LValue's
7166/// record layout. e.g.
7167/// struct { struct { int a, b; } fst, snd; } obj;
7168/// obj.fst // no
7169/// obj.snd // yes
7170/// obj.fst.a // no
7171/// obj.fst.b // no
7172/// obj.snd.a // no
7173/// obj.snd.b // yes
7174///
7175/// Please note: this function is specialized for how __builtin_object_size
7176/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007177///
7178/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007179static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7180 assert(!LVal.Designator.Invalid);
7181
George Burgess IV4168d752016-06-27 19:40:41 +00007182 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7183 const RecordDecl *Parent = FD->getParent();
7184 Invalid = Parent->isInvalidDecl();
7185 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007186 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007187 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007188 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7189 };
7190
7191 auto &Base = LVal.getLValueBase();
7192 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7193 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007194 bool Invalid;
7195 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7196 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007197 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007198 for (auto *FD : IFD->chain()) {
7199 bool Invalid;
7200 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7201 return Invalid;
7202 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007203 }
7204 }
7205
George Burgess IVe3763372016-12-22 02:50:20 +00007206 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007207 QualType BaseType = getType(Base);
George Burgess IVe3763372016-12-22 02:50:20 +00007208 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7209 assert(isBaseAnAllocSizeCall(Base) &&
7210 "Unsized array in non-alloc_size call?");
7211 // If this is an alloc_size base, we should ignore the initial array index
7212 ++I;
7213 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7214 }
7215
7216 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7217 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007218 if (BaseType->isArrayType()) {
7219 // Because __builtin_object_size treats arrays as objects, we can ignore
7220 // the index iff this is the last array in the Designator.
7221 if (I + 1 == E)
7222 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007223 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7224 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007225 if (Index + 1 != CAT->getSize())
7226 return false;
7227 BaseType = CAT->getElementType();
7228 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007229 const auto *CT = BaseType->castAs<ComplexType>();
7230 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007231 if (Index != 1)
7232 return false;
7233 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007234 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007235 bool Invalid;
7236 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7237 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007238 BaseType = FD->getType();
7239 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007240 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007241 return false;
7242 }
7243 }
7244 return true;
7245}
7246
George Burgess IVe3763372016-12-22 02:50:20 +00007247/// Tests to see if the LValue has a user-specified designator (that isn't
7248/// necessarily valid). Note that this always returns 'true' if the LValue has
7249/// an unsized array as its first designator entry, because there's currently no
7250/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007251static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007252 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007253 return false;
7254
George Burgess IVe3763372016-12-22 02:50:20 +00007255 if (!LVal.Designator.Entries.empty())
7256 return LVal.Designator.isMostDerivedAnUnsizedArray();
7257
George Burgess IVa51c4072015-10-16 01:49:01 +00007258 if (!LVal.InvalidBase)
7259 return true;
7260
George Burgess IVe3763372016-12-22 02:50:20 +00007261 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7262 // the LValueBase.
7263 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7264 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007265}
7266
George Burgess IVe3763372016-12-22 02:50:20 +00007267/// Attempts to detect a user writing into a piece of memory that's impossible
7268/// to figure out the size of by just using types.
7269static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7270 const SubobjectDesignator &Designator = LVal.Designator;
7271 // Notes:
7272 // - Users can only write off of the end when we have an invalid base. Invalid
7273 // bases imply we don't know where the memory came from.
7274 // - We used to be a bit more aggressive here; we'd only be conservative if
7275 // the array at the end was flexible, or if it had 0 or 1 elements. This
7276 // broke some common standard library extensions (PR30346), but was
7277 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7278 // with some sort of whitelist. OTOH, it seems that GCC is always
7279 // conservative with the last element in structs (if it's an array), so our
7280 // current behavior is more compatible than a whitelisting approach would
7281 // be.
7282 return LVal.InvalidBase &&
7283 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7284 Designator.MostDerivedIsArrayElement &&
7285 isDesignatorAtObjectEnd(Ctx, LVal);
7286}
7287
7288/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7289/// Fails if the conversion would cause loss of precision.
7290static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7291 CharUnits &Result) {
7292 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7293 if (Int.ugt(CharUnitsMax))
7294 return false;
7295 Result = CharUnits::fromQuantity(Int.getZExtValue());
7296 return true;
7297}
7298
7299/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7300/// determine how many bytes exist from the beginning of the object to either
7301/// the end of the current subobject, or the end of the object itself, depending
7302/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007303///
George Burgess IVe3763372016-12-22 02:50:20 +00007304/// If this returns false, the value of Result is undefined.
7305static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7306 unsigned Type, const LValue &LVal,
7307 CharUnits &EndOffset) {
7308 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007309
George Burgess IV7fb7e362017-01-03 23:35:19 +00007310 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7311 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7312 return false;
7313 return HandleSizeof(Info, ExprLoc, Ty, Result);
7314 };
7315
George Burgess IVe3763372016-12-22 02:50:20 +00007316 // We want to evaluate the size of the entire object. This is a valid fallback
7317 // for when Type=1 and the designator is invalid, because we're asked for an
7318 // upper-bound.
7319 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7320 // Type=3 wants a lower bound, so we can't fall back to this.
7321 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007322 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007323
7324 llvm::APInt APEndOffset;
7325 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7326 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7327 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7328
7329 if (LVal.InvalidBase)
7330 return false;
7331
7332 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007333 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007334 }
7335
George Burgess IVe3763372016-12-22 02:50:20 +00007336 // We want to evaluate the size of a subobject.
7337 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007338
7339 // The following is a moderately common idiom in C:
7340 //
7341 // struct Foo { int a; char c[1]; };
7342 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7343 // strcpy(&F->c[0], Bar);
7344 //
George Burgess IVe3763372016-12-22 02:50:20 +00007345 // In order to not break too much legacy code, we need to support it.
7346 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7347 // If we can resolve this to an alloc_size call, we can hand that back,
7348 // because we know for certain how many bytes there are to write to.
7349 llvm::APInt APEndOffset;
7350 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7351 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7352 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7353
7354 // If we cannot determine the size of the initial allocation, then we can't
7355 // given an accurate upper-bound. However, we are still able to give
7356 // conservative lower-bounds for Type=3.
7357 if (Type == 1)
7358 return false;
7359 }
7360
7361 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007362 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007363 return false;
7364
George Burgess IVe3763372016-12-22 02:50:20 +00007365 // According to the GCC documentation, we want the size of the subobject
7366 // denoted by the pointer. But that's not quite right -- what we actually
7367 // want is the size of the immediately-enclosing array, if there is one.
7368 int64_t ElemsRemaining;
7369 if (Designator.MostDerivedIsArrayElement &&
7370 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7371 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7372 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7373 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7374 } else {
7375 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7376 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007377
George Burgess IVe3763372016-12-22 02:50:20 +00007378 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7379 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007380}
7381
George Burgess IVe3763372016-12-22 02:50:20 +00007382/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7383/// returns true and stores the result in @p Size.
7384///
7385/// If @p WasError is non-null, this will report whether the failure to evaluate
7386/// is to be treated as an Error in IntExprEvaluator.
7387static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7388 EvalInfo &Info, uint64_t &Size) {
7389 // Determine the denoted object.
7390 LValue LVal;
7391 {
7392 // The operand of __builtin_object_size is never evaluated for side-effects.
7393 // If there are any, but we can determine the pointed-to object anyway, then
7394 // ignore the side-effects.
7395 SpeculativeEvaluationRAII SpeculativeEval(Info);
7396 FoldOffsetRAII Fold(Info);
7397
7398 if (E->isGLValue()) {
7399 // It's possible for us to be given GLValues if we're called via
7400 // Expr::tryEvaluateObjectSize.
7401 APValue RVal;
7402 if (!EvaluateAsRValue(Info, E, RVal))
7403 return false;
7404 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007405 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7406 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007407 return false;
7408 }
7409
7410 // If we point to before the start of the object, there are no accessible
7411 // bytes.
7412 if (LVal.getLValueOffset().isNegative()) {
7413 Size = 0;
7414 return true;
7415 }
7416
7417 CharUnits EndOffset;
7418 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7419 return false;
7420
7421 // If we've fallen outside of the end offset, just pretend there's nothing to
7422 // write to/read from.
7423 if (EndOffset <= LVal.getLValueOffset())
7424 Size = 0;
7425 else
7426 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7427 return true;
John McCall95007602010-05-10 23:27:23 +00007428}
7429
Peter Collingbournee9200682011-05-13 03:29:01 +00007430bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007431 if (unsigned BuiltinOp = E->getBuiltinCallee())
7432 return VisitBuiltinCallExpr(E, BuiltinOp);
7433
7434 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7435}
7436
7437bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7438 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007439 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007440 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007441 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007442
7443 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007444 // The type was checked when we built the expression.
7445 unsigned Type =
7446 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7447 assert(Type <= 3 && "unexpected type");
7448
George Burgess IVe3763372016-12-22 02:50:20 +00007449 uint64_t Size;
7450 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7451 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007452
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007453 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007454 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007455
Richard Smith01ade172012-05-23 04:13:20 +00007456 // Expression had no side effects, but we couldn't statically determine the
7457 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007458 switch (Info.EvalMode) {
7459 case EvalInfo::EM_ConstantExpression:
7460 case EvalInfo::EM_PotentialConstantExpression:
7461 case EvalInfo::EM_ConstantFold:
7462 case EvalInfo::EM_EvaluateForOverflow:
7463 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007464 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007465 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007466 return Error(E);
7467 case EvalInfo::EM_ConstantExpressionUnevaluated:
7468 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007469 // Reduce it to a constant now.
7470 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007471 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007472
7473 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007474 }
7475
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007476 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007477 case Builtin::BI__builtin_bswap32:
7478 case Builtin::BI__builtin_bswap64: {
7479 APSInt Val;
7480 if (!EvaluateInteger(E->getArg(0), Val, Info))
7481 return false;
7482
7483 return Success(Val.byteSwap(), E);
7484 }
7485
Richard Smith8889a3d2013-06-13 06:26:32 +00007486 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007487 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007488
7489 // FIXME: BI__builtin_clrsb
7490 // FIXME: BI__builtin_clrsbl
7491 // FIXME: BI__builtin_clrsbll
7492
Richard Smith80b3c8e2013-06-13 05:04:16 +00007493 case Builtin::BI__builtin_clz:
7494 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007495 case Builtin::BI__builtin_clzll:
7496 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007497 APSInt Val;
7498 if (!EvaluateInteger(E->getArg(0), Val, Info))
7499 return false;
7500 if (!Val)
7501 return Error(E);
7502
7503 return Success(Val.countLeadingZeros(), E);
7504 }
7505
Richard Smith8889a3d2013-06-13 06:26:32 +00007506 case Builtin::BI__builtin_constant_p:
7507 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7508
Richard Smith80b3c8e2013-06-13 05:04:16 +00007509 case Builtin::BI__builtin_ctz:
7510 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007511 case Builtin::BI__builtin_ctzll:
7512 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007513 APSInt Val;
7514 if (!EvaluateInteger(E->getArg(0), Val, Info))
7515 return false;
7516 if (!Val)
7517 return Error(E);
7518
7519 return Success(Val.countTrailingZeros(), E);
7520 }
7521
Richard Smith8889a3d2013-06-13 06:26:32 +00007522 case Builtin::BI__builtin_eh_return_data_regno: {
7523 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7524 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7525 return Success(Operand, E);
7526 }
7527
7528 case Builtin::BI__builtin_expect:
7529 return Visit(E->getArg(0));
7530
7531 case Builtin::BI__builtin_ffs:
7532 case Builtin::BI__builtin_ffsl:
7533 case Builtin::BI__builtin_ffsll: {
7534 APSInt Val;
7535 if (!EvaluateInteger(E->getArg(0), Val, Info))
7536 return false;
7537
7538 unsigned N = Val.countTrailingZeros();
7539 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7540 }
7541
7542 case Builtin::BI__builtin_fpclassify: {
7543 APFloat Val(0.0);
7544 if (!EvaluateFloat(E->getArg(5), Val, Info))
7545 return false;
7546 unsigned Arg;
7547 switch (Val.getCategory()) {
7548 case APFloat::fcNaN: Arg = 0; break;
7549 case APFloat::fcInfinity: Arg = 1; break;
7550 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7551 case APFloat::fcZero: Arg = 4; break;
7552 }
7553 return Visit(E->getArg(Arg));
7554 }
7555
7556 case Builtin::BI__builtin_isinf_sign: {
7557 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007558 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007559 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7560 }
7561
Richard Smithea3019d2013-10-15 19:07:14 +00007562 case Builtin::BI__builtin_isinf: {
7563 APFloat Val(0.0);
7564 return EvaluateFloat(E->getArg(0), Val, Info) &&
7565 Success(Val.isInfinity() ? 1 : 0, E);
7566 }
7567
7568 case Builtin::BI__builtin_isfinite: {
7569 APFloat Val(0.0);
7570 return EvaluateFloat(E->getArg(0), Val, Info) &&
7571 Success(Val.isFinite() ? 1 : 0, E);
7572 }
7573
7574 case Builtin::BI__builtin_isnan: {
7575 APFloat Val(0.0);
7576 return EvaluateFloat(E->getArg(0), Val, Info) &&
7577 Success(Val.isNaN() ? 1 : 0, E);
7578 }
7579
7580 case Builtin::BI__builtin_isnormal: {
7581 APFloat Val(0.0);
7582 return EvaluateFloat(E->getArg(0), Val, Info) &&
7583 Success(Val.isNormal() ? 1 : 0, E);
7584 }
7585
Richard Smith8889a3d2013-06-13 06:26:32 +00007586 case Builtin::BI__builtin_parity:
7587 case Builtin::BI__builtin_parityl:
7588 case Builtin::BI__builtin_parityll: {
7589 APSInt Val;
7590 if (!EvaluateInteger(E->getArg(0), Val, Info))
7591 return false;
7592
7593 return Success(Val.countPopulation() % 2, E);
7594 }
7595
Richard Smith80b3c8e2013-06-13 05:04:16 +00007596 case Builtin::BI__builtin_popcount:
7597 case Builtin::BI__builtin_popcountl:
7598 case Builtin::BI__builtin_popcountll: {
7599 APSInt Val;
7600 if (!EvaluateInteger(E->getArg(0), Val, Info))
7601 return false;
7602
7603 return Success(Val.countPopulation(), E);
7604 }
7605
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007606 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007607 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007608 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007609 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007610 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007611 << /*isConstexpr*/0 << /*isConstructor*/0
7612 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007613 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007614 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007615 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007616 case Builtin::BI__builtin_strlen:
7617 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007618 // As an extension, we support __builtin_strlen() as a constant expression,
7619 // and support folding strlen() to a constant.
7620 LValue String;
7621 if (!EvaluatePointer(E->getArg(0), String, Info))
7622 return false;
7623
Richard Smith8110c9d2016-11-29 19:45:17 +00007624 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7625
Richard Smithe6c19f22013-11-15 02:10:04 +00007626 // Fast path: if it's a string literal, search the string value.
7627 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7628 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007629 // The string literal may have embedded null characters. Find the first
7630 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007631 StringRef Str = S->getBytes();
7632 int64_t Off = String.Offset.getQuantity();
7633 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007634 S->getCharByteWidth() == 1 &&
7635 // FIXME: Add fast-path for wchar_t too.
7636 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007637 Str = Str.substr(Off);
7638
7639 StringRef::size_type Pos = Str.find(0);
7640 if (Pos != StringRef::npos)
7641 Str = Str.substr(0, Pos);
7642
7643 return Success(Str.size(), E);
7644 }
7645
7646 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007647 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007648
7649 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007650 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7651 APValue Char;
7652 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7653 !Char.isInt())
7654 return false;
7655 if (!Char.getInt())
7656 return Success(Strlen, E);
7657 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7658 return false;
7659 }
7660 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007661
Richard Smithe151bab2016-11-11 23:43:35 +00007662 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007663 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007664 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007665 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007666 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007667 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007668 // A call to strlen is not a constant expression.
7669 if (Info.getLangOpts().CPlusPlus11)
7670 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7671 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007672 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007673 else
7674 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7675 // Fall through.
7676 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007677 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007678 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007679 case Builtin::BI__builtin_wcsncmp:
7680 case Builtin::BI__builtin_memcmp:
7681 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007682 LValue String1, String2;
7683 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7684 !EvaluatePointer(E->getArg(1), String2, Info))
7685 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007686
7687 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7688
Richard Smithe151bab2016-11-11 23:43:35 +00007689 uint64_t MaxLength = uint64_t(-1);
7690 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007691 BuiltinOp != Builtin::BIwcscmp &&
7692 BuiltinOp != Builtin::BI__builtin_strcmp &&
7693 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007694 APSInt N;
7695 if (!EvaluateInteger(E->getArg(2), N, Info))
7696 return false;
7697 MaxLength = N.getExtValue();
7698 }
7699 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007700 BuiltinOp != Builtin::BIwmemcmp &&
7701 BuiltinOp != Builtin::BI__builtin_memcmp &&
7702 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007703 for (; MaxLength; --MaxLength) {
7704 APValue Char1, Char2;
7705 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7706 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7707 !Char1.isInt() || !Char2.isInt())
7708 return false;
7709 if (Char1.getInt() != Char2.getInt())
7710 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7711 if (StopAtNull && !Char1.getInt())
7712 return Success(0, E);
7713 assert(!(StopAtNull && !Char2.getInt()));
7714 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7715 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7716 return false;
7717 }
7718 // We hit the strncmp / memcmp limit.
7719 return Success(0, E);
7720 }
7721
Richard Smith01ba47d2012-04-13 00:45:38 +00007722 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007723 case Builtin::BI__atomic_is_lock_free:
7724 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007725 APSInt SizeVal;
7726 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7727 return false;
7728
7729 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7730 // of two less than the maximum inline atomic width, we know it is
7731 // lock-free. If the size isn't a power of two, or greater than the
7732 // maximum alignment where we promote atomics, we know it is not lock-free
7733 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7734 // the answer can only be determined at runtime; for example, 16-byte
7735 // atomics have lock-free implementations on some, but not all,
7736 // x86-64 processors.
7737
7738 // Check power-of-two.
7739 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007740 if (Size.isPowerOfTwo()) {
7741 // Check against inlining width.
7742 unsigned InlineWidthBits =
7743 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7744 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7745 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7746 Size == CharUnits::One() ||
7747 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7748 Expr::NPC_NeverValueDependent))
7749 // OK, we will inline appropriately-aligned operations of this size,
7750 // and _Atomic(T) is appropriately-aligned.
7751 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007752
Richard Smith01ba47d2012-04-13 00:45:38 +00007753 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7754 castAs<PointerType>()->getPointeeType();
7755 if (!PointeeType->isIncompleteType() &&
7756 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7757 // OK, we will inline operations on this object.
7758 return Success(1, E);
7759 }
7760 }
7761 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007762
Richard Smith01ba47d2012-04-13 00:45:38 +00007763 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7764 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007765 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007766 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007767}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007768
Richard Smith8b3497e2011-10-31 01:37:14 +00007769static bool HasSameBase(const LValue &A, const LValue &B) {
7770 if (!A.getLValueBase())
7771 return !B.getLValueBase();
7772 if (!B.getLValueBase())
7773 return false;
7774
Richard Smithce40ad62011-11-12 22:28:03 +00007775 if (A.getLValueBase().getOpaqueValue() !=
7776 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007777 const Decl *ADecl = GetLValueBaseDecl(A);
7778 if (!ADecl)
7779 return false;
7780 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007781 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007782 return false;
7783 }
7784
7785 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007786 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007787}
7788
Richard Smithd20f1e62014-10-21 23:01:04 +00007789/// \brief Determine whether this is a pointer past the end of the complete
7790/// object referred to by the lvalue.
7791static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7792 const LValue &LV) {
7793 // A null pointer can be viewed as being "past the end" but we don't
7794 // choose to look at it that way here.
7795 if (!LV.getLValueBase())
7796 return false;
7797
7798 // If the designator is valid and refers to a subobject, we're not pointing
7799 // past the end.
7800 if (!LV.getLValueDesignator().Invalid &&
7801 !LV.getLValueDesignator().isOnePastTheEnd())
7802 return false;
7803
David Majnemerc378ca52015-08-29 08:32:55 +00007804 // A pointer to an incomplete type might be past-the-end if the type's size is
7805 // zero. We cannot tell because the type is incomplete.
7806 QualType Ty = getType(LV.getLValueBase());
7807 if (Ty->isIncompleteType())
7808 return true;
7809
Richard Smithd20f1e62014-10-21 23:01:04 +00007810 // We're a past-the-end pointer if we point to the byte after the object,
7811 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007812 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007813 return LV.getLValueOffset() == Size;
7814}
7815
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007816namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007817
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007818/// \brief Data recursive integer evaluator of certain binary operators.
7819///
7820/// We use a data recursive algorithm for binary operators so that we are able
7821/// to handle extreme cases of chained binary operators without causing stack
7822/// overflow.
7823class DataRecursiveIntBinOpEvaluator {
7824 struct EvalResult {
7825 APValue Val;
7826 bool Failed;
7827
7828 EvalResult() : Failed(false) { }
7829
7830 void swap(EvalResult &RHS) {
7831 Val.swap(RHS.Val);
7832 Failed = RHS.Failed;
7833 RHS.Failed = false;
7834 }
7835 };
7836
7837 struct Job {
7838 const Expr *E;
7839 EvalResult LHSResult; // meaningful only for binary operator expression.
7840 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007841
David Blaikie73726062015-08-12 23:09:24 +00007842 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007843 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007844
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007845 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007846 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007847 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007848
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007849 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007850 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007851 };
7852
7853 SmallVector<Job, 16> Queue;
7854
7855 IntExprEvaluator &IntEval;
7856 EvalInfo &Info;
7857 APValue &FinalResult;
7858
7859public:
7860 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7861 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7862
7863 /// \brief True if \param E is a binary operator that we are going to handle
7864 /// data recursively.
7865 /// We handle binary operators that are comma, logical, or that have operands
7866 /// with integral or enumeration type.
7867 static bool shouldEnqueue(const BinaryOperator *E) {
7868 return E->getOpcode() == BO_Comma ||
7869 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007870 (E->isRValue() &&
7871 E->getType()->isIntegralOrEnumerationType() &&
7872 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007873 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007874 }
7875
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007876 bool Traverse(const BinaryOperator *E) {
7877 enqueue(E);
7878 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007879 while (!Queue.empty())
7880 process(PrevResult);
7881
7882 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007883
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007884 FinalResult.swap(PrevResult.Val);
7885 return true;
7886 }
7887
7888private:
7889 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7890 return IntEval.Success(Value, E, Result);
7891 }
7892 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7893 return IntEval.Success(Value, E, Result);
7894 }
7895 bool Error(const Expr *E) {
7896 return IntEval.Error(E);
7897 }
7898 bool Error(const Expr *E, diag::kind D) {
7899 return IntEval.Error(E, D);
7900 }
7901
7902 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7903 return Info.CCEDiag(E, D);
7904 }
7905
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007906 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7907 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007908 bool &SuppressRHSDiags);
7909
7910 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7911 const BinaryOperator *E, APValue &Result);
7912
7913 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7914 Result.Failed = !Evaluate(Result.Val, Info, E);
7915 if (Result.Failed)
7916 Result.Val = APValue();
7917 }
7918
Richard Trieuba4d0872012-03-21 23:30:30 +00007919 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007920
7921 void enqueue(const Expr *E) {
7922 E = E->IgnoreParens();
7923 Queue.resize(Queue.size()+1);
7924 Queue.back().E = E;
7925 Queue.back().Kind = Job::AnyExprKind;
7926 }
7927};
7928
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007929}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007930
7931bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007932 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007933 bool &SuppressRHSDiags) {
7934 if (E->getOpcode() == BO_Comma) {
7935 // Ignore LHS but note if we could not evaluate it.
7936 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007937 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007938 return true;
7939 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007940
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007941 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007942 bool LHSAsBool;
7943 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007944 // We were able to evaluate the LHS, see if we can get away with not
7945 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007946 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7947 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007948 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007949 }
7950 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007951 LHSResult.Failed = true;
7952
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007953 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00007954 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007955 if (!Info.noteSideEffect())
7956 return false;
7957
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007958 // We can't evaluate the LHS; however, sometimes the result
7959 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7960 // Don't ignore RHS and suppress diagnostics from this arm.
7961 SuppressRHSDiags = true;
7962 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007963
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007964 return true;
7965 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007966
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007967 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7968 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007969
George Burgess IVa145e252016-05-25 22:38:36 +00007970 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007971 return false; // Ignore RHS;
7972
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007973 return true;
7974}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007975
Richard Smithd6cc1982017-01-31 02:23:02 +00007976static void addOrSubLValueAsInteger(APValue &LVal, APSInt Index, bool IsSub) {
7977 // Compute the new offset in the appropriate width, wrapping at 64 bits.
7978 // FIXME: When compiling for a 32-bit target, we should use 32-bit
7979 // offsets.
7980 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
7981 CharUnits &Offset = LVal.getLValueOffset();
7982 uint64_t Offset64 = Offset.getQuantity();
7983 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
7984 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
7985 : Offset64 + Index64);
7986}
7987
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007988bool DataRecursiveIntBinOpEvaluator::
7989 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7990 const BinaryOperator *E, APValue &Result) {
7991 if (E->getOpcode() == BO_Comma) {
7992 if (RHSResult.Failed)
7993 return false;
7994 Result = RHSResult.Val;
7995 return true;
7996 }
7997
7998 if (E->isLogicalOp()) {
7999 bool lhsResult, rhsResult;
8000 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8001 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
8002
8003 if (LHSIsOK) {
8004 if (RHSIsOK) {
8005 if (E->getOpcode() == BO_LOr)
8006 return Success(lhsResult || rhsResult, E, Result);
8007 else
8008 return Success(lhsResult && rhsResult, E, Result);
8009 }
8010 } else {
8011 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008012 // We can't evaluate the LHS; however, sometimes the result
8013 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8014 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008015 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008016 }
8017 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008018
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008019 return false;
8020 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008021
8022 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8023 E->getRHS()->getType()->isIntegralOrEnumerationType());
8024
8025 if (LHSResult.Failed || RHSResult.Failed)
8026 return false;
8027
8028 const APValue &LHSVal = LHSResult.Val;
8029 const APValue &RHSVal = RHSResult.Val;
8030
8031 // Handle cases like (unsigned long)&a + 4.
8032 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8033 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008034 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008035 return true;
8036 }
8037
8038 // Handle cases like 4 + (unsigned long)&a
8039 if (E->getOpcode() == BO_Add &&
8040 RHSVal.isLValue() && LHSVal.isInt()) {
8041 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008042 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008043 return true;
8044 }
8045
8046 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8047 // Handle (intptr_t)&&A - (intptr_t)&&B.
8048 if (!LHSVal.getLValueOffset().isZero() ||
8049 !RHSVal.getLValueOffset().isZero())
8050 return false;
8051 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8052 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8053 if (!LHSExpr || !RHSExpr)
8054 return false;
8055 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8056 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8057 if (!LHSAddrExpr || !RHSAddrExpr)
8058 return false;
8059 // Make sure both labels come from the same function.
8060 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8061 RHSAddrExpr->getLabel()->getDeclContext())
8062 return false;
8063 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8064 return true;
8065 }
Richard Smith43e77732013-05-07 04:50:00 +00008066
8067 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008068 if (!LHSVal.isInt() || !RHSVal.isInt())
8069 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008070
8071 // Set up the width and signedness manually, in case it can't be deduced
8072 // from the operation we're performing.
8073 // FIXME: Don't do this in the cases where we can deduce it.
8074 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8075 E->getType()->isUnsignedIntegerOrEnumerationType());
8076 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8077 RHSVal.getInt(), Value))
8078 return false;
8079 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008080}
8081
Richard Trieuba4d0872012-03-21 23:30:30 +00008082void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008083 Job &job = Queue.back();
8084
8085 switch (job.Kind) {
8086 case Job::AnyExprKind: {
8087 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8088 if (shouldEnqueue(Bop)) {
8089 job.Kind = Job::BinOpKind;
8090 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008091 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008092 }
8093 }
8094
8095 EvaluateExpr(job.E, Result);
8096 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008097 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008098 }
8099
8100 case Job::BinOpKind: {
8101 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008102 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008103 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008104 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008105 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008106 }
8107 if (SuppressRHSDiags)
8108 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008109 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008110 job.Kind = Job::BinOpVisitedLHSKind;
8111 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008112 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008113 }
8114
8115 case Job::BinOpVisitedLHSKind: {
8116 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8117 EvalResult RHS;
8118 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008119 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008120 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008121 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008122 }
8123 }
8124
8125 llvm_unreachable("Invalid Job::Kind!");
8126}
8127
George Burgess IV8c892b52016-05-25 22:31:54 +00008128namespace {
8129/// Used when we determine that we should fail, but can keep evaluating prior to
8130/// noting that we had a failure.
8131class DelayedNoteFailureRAII {
8132 EvalInfo &Info;
8133 bool NoteFailure;
8134
8135public:
8136 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8137 : Info(Info), NoteFailure(NoteFailure) {}
8138 ~DelayedNoteFailureRAII() {
8139 if (NoteFailure) {
8140 bool ContinueAfterFailure = Info.noteFailure();
8141 (void)ContinueAfterFailure;
8142 assert(ContinueAfterFailure &&
8143 "Shouldn't have kept evaluating on failure.");
8144 }
8145 }
8146};
8147}
8148
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008149bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008150 // We don't call noteFailure immediately because the assignment happens after
8151 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008152 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008153 return Error(E);
8154
George Burgess IV8c892b52016-05-25 22:31:54 +00008155 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008156 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8157 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008158
Anders Carlssonacc79812008-11-16 07:17:21 +00008159 QualType LHSTy = E->getLHS()->getType();
8160 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008161
Chandler Carruthb29a7432014-10-11 11:03:30 +00008162 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008163 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008164 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008165 if (E->isAssignmentOp()) {
8166 LValue LV;
8167 EvaluateLValue(E->getLHS(), LV, Info);
8168 LHSOK = false;
8169 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008170 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8171 if (LHSOK) {
8172 LHS.makeComplexFloat();
8173 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8174 }
8175 } else {
8176 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8177 }
George Burgess IVa145e252016-05-25 22:38:36 +00008178 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008179 return false;
8180
Chandler Carruthb29a7432014-10-11 11:03:30 +00008181 if (E->getRHS()->getType()->isRealFloatingType()) {
8182 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8183 return false;
8184 RHS.makeComplexFloat();
8185 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8186 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008187 return false;
8188
8189 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008190 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008191 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008192 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008193 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8194
John McCalle3027922010-08-25 11:45:40 +00008195 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008196 return Success((CR_r == APFloat::cmpEqual &&
8197 CR_i == APFloat::cmpEqual), E);
8198 else {
John McCalle3027922010-08-25 11:45:40 +00008199 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008200 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008201 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008202 CR_r == APFloat::cmpLessThan ||
8203 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008204 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008205 CR_i == APFloat::cmpLessThan ||
8206 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008207 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008208 } else {
John McCalle3027922010-08-25 11:45:40 +00008209 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008210 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8211 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8212 else {
John McCalle3027922010-08-25 11:45:40 +00008213 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008214 "Invalid compex comparison.");
8215 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8216 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8217 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008218 }
8219 }
Mike Stump11289f42009-09-09 15:08:12 +00008220
Anders Carlssonacc79812008-11-16 07:17:21 +00008221 if (LHSTy->isRealFloatingType() &&
8222 RHSTy->isRealFloatingType()) {
8223 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008224
Richard Smith253c2a32012-01-27 01:14:48 +00008225 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008226 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008227 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008228
Richard Smith253c2a32012-01-27 01:14:48 +00008229 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008230 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008231
Anders Carlssonacc79812008-11-16 07:17:21 +00008232 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008233
Anders Carlssonacc79812008-11-16 07:17:21 +00008234 switch (E->getOpcode()) {
8235 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008236 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008237 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008238 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008239 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008240 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008241 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008242 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008243 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008244 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008245 E);
John McCalle3027922010-08-25 11:45:40 +00008246 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008247 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008248 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008249 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008250 || CR == APFloat::cmpLessThan
8251 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008252 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008253 }
Mike Stump11289f42009-09-09 15:08:12 +00008254
Eli Friedmana38da572009-04-28 19:17:36 +00008255 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008256 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008257 LValue LHSValue, RHSValue;
8258
8259 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008260 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008261 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008262
Richard Smith253c2a32012-01-27 01:14:48 +00008263 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008264 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008265
Richard Smith8b3497e2011-10-31 01:37:14 +00008266 // Reject differing bases from the normal codepath; we special-case
8267 // comparisons to null.
8268 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008269 if (E->getOpcode() == BO_Sub) {
8270 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008271 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008272 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008273 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008274 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008275 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008276 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008277 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8278 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8279 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008280 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008281 // Make sure both labels come from the same function.
8282 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8283 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008284 return Error(E);
8285 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008286 }
Richard Smith83c68212011-10-31 05:11:32 +00008287 // Inequalities and subtractions between unrelated pointers have
8288 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008289 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008290 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008291 // A constant address may compare equal to the address of a symbol.
8292 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008293 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008294 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8295 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008296 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008297 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008298 // distinct addresses. In clang, the result of such a comparison is
8299 // unspecified, so it is not a constant expression. However, we do know
8300 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008301 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8302 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008303 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008304 // We can't tell whether weak symbols will end up pointing to the same
8305 // object.
8306 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008307 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008308 // We can't compare the address of the start of one object with the
8309 // past-the-end address of another object, per C++ DR1652.
8310 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8311 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8312 (RHSValue.Base && RHSValue.Offset.isZero() &&
8313 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8314 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008315 // We can't tell whether an object is at the same address as another
8316 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008317 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8318 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008319 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008320 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008321 // (Note that clang defaults to -fmerge-all-constants, which can
8322 // lead to inconsistent results for comparisons involving the address
8323 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008324 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008325 }
Eli Friedman64004332009-03-23 04:38:34 +00008326
Richard Smith1b470412012-02-01 08:10:20 +00008327 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8328 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8329
Richard Smith84f6dcf2012-02-02 01:16:57 +00008330 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8331 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8332
John McCalle3027922010-08-25 11:45:40 +00008333 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008334 // C++11 [expr.add]p6:
8335 // Unless both pointers point to elements of the same array object, or
8336 // one past the last element of the array object, the behavior is
8337 // undefined.
8338 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8339 !AreElementsOfSameArray(getType(LHSValue.Base),
8340 LHSDesignator, RHSDesignator))
8341 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8342
Chris Lattner882bdf22010-04-20 17:13:14 +00008343 QualType Type = E->getLHS()->getType();
8344 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008345
Richard Smithd62306a2011-11-10 06:34:14 +00008346 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008347 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008348 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008349
Richard Smith84c6b3d2013-09-10 21:34:14 +00008350 // As an extension, a type may have zero size (empty struct or union in
8351 // C, array of zero length). Pointer subtraction in such cases has
8352 // undefined behavior, so is not constant.
8353 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008354 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008355 << ElementType;
8356 return false;
8357 }
8358
Richard Smith1b470412012-02-01 08:10:20 +00008359 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8360 // and produce incorrect results when it overflows. Such behavior
8361 // appears to be non-conforming, but is common, so perhaps we should
8362 // assume the standard intended for such cases to be undefined behavior
8363 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008364
Richard Smith1b470412012-02-01 08:10:20 +00008365 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8366 // overflow in the final conversion to ptrdiff_t.
8367 APSInt LHS(
8368 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8369 APSInt RHS(
8370 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8371 APSInt ElemSize(
8372 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8373 APSInt TrueResult = (LHS - RHS) / ElemSize;
8374 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8375
Richard Smith0c6124b2015-12-03 01:36:22 +00008376 if (Result.extend(65) != TrueResult &&
8377 !HandleOverflow(Info, E, TrueResult, E->getType()))
8378 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008379 return Success(Result, E);
8380 }
Richard Smithde21b242012-01-31 06:41:30 +00008381
8382 // C++11 [expr.rel]p3:
8383 // Pointers to void (after pointer conversions) can be compared, with a
8384 // result defined as follows: If both pointers represent the same
8385 // address or are both the null pointer value, the result is true if the
8386 // operator is <= or >= and false otherwise; otherwise the result is
8387 // unspecified.
8388 // We interpret this as applying to pointers to *cv* void.
8389 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008390 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008391 CCEDiag(E, diag::note_constexpr_void_comparison);
8392
Richard Smith84f6dcf2012-02-02 01:16:57 +00008393 // C++11 [expr.rel]p2:
8394 // - If two pointers point to non-static data members of the same object,
8395 // or to subobjects or array elements fo such members, recursively, the
8396 // pointer to the later declared member compares greater provided the
8397 // two members have the same access control and provided their class is
8398 // not a union.
8399 // [...]
8400 // - Otherwise pointer comparisons are unspecified.
8401 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8402 E->isRelationalOp()) {
8403 bool WasArrayIndex;
8404 unsigned Mismatch =
8405 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8406 RHSDesignator, WasArrayIndex);
8407 // At the point where the designators diverge, the comparison has a
8408 // specified value if:
8409 // - we are comparing array indices
8410 // - we are comparing fields of a union, or fields with the same access
8411 // Otherwise, the result is unspecified and thus the comparison is not a
8412 // constant expression.
8413 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8414 Mismatch < RHSDesignator.Entries.size()) {
8415 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8416 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8417 if (!LF && !RF)
8418 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8419 else if (!LF)
8420 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8421 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8422 << RF->getParent() << RF;
8423 else if (!RF)
8424 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8425 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8426 << LF->getParent() << LF;
8427 else if (!LF->getParent()->isUnion() &&
8428 LF->getAccess() != RF->getAccess())
8429 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8430 << LF << LF->getAccess() << RF << RF->getAccess()
8431 << LF->getParent();
8432 }
8433 }
8434
Eli Friedman6c31cb42012-04-16 04:30:08 +00008435 // The comparison here must be unsigned, and performed with the same
8436 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008437 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8438 uint64_t CompareLHS = LHSOffset.getQuantity();
8439 uint64_t CompareRHS = RHSOffset.getQuantity();
8440 assert(PtrSize <= 64 && "Unexpected pointer width");
8441 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8442 CompareLHS &= Mask;
8443 CompareRHS &= Mask;
8444
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008445 // If there is a base and this is a relational operator, we can only
8446 // compare pointers within the object in question; otherwise, the result
8447 // depends on where the object is located in memory.
8448 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8449 QualType BaseTy = getType(LHSValue.Base);
8450 if (BaseTy->isIncompleteType())
8451 return Error(E);
8452 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8453 uint64_t OffsetLimit = Size.getQuantity();
8454 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8455 return Error(E);
8456 }
8457
Richard Smith8b3497e2011-10-31 01:37:14 +00008458 switch (E->getOpcode()) {
8459 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008460 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8461 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8462 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8463 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8464 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8465 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008466 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008467 }
8468 }
Richard Smith7bb00672012-02-01 01:42:44 +00008469
8470 if (LHSTy->isMemberPointerType()) {
8471 assert(E->isEqualityOp() && "unexpected member pointer operation");
8472 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8473
8474 MemberPtr LHSValue, RHSValue;
8475
8476 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008477 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008478 return false;
8479
8480 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8481 return false;
8482
8483 // C++11 [expr.eq]p2:
8484 // If both operands are null, they compare equal. Otherwise if only one is
8485 // null, they compare unequal.
8486 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8487 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8488 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8489 }
8490
8491 // Otherwise if either is a pointer to a virtual member function, the
8492 // result is unspecified.
8493 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8494 if (MD->isVirtual())
8495 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8496 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8497 if (MD->isVirtual())
8498 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8499
8500 // Otherwise they compare equal if and only if they would refer to the
8501 // same member of the same most derived object or the same subobject if
8502 // they were dereferenced with a hypothetical object of the associated
8503 // class type.
8504 bool Equal = LHSValue == RHSValue;
8505 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8506 }
8507
Richard Smithab44d9b2012-02-14 22:35:28 +00008508 if (LHSTy->isNullPtrType()) {
8509 assert(E->isComparisonOp() && "unexpected nullptr operation");
8510 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8511 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8512 // are compared, the result is true of the operator is <=, >= or ==, and
8513 // false otherwise.
8514 BinaryOperator::Opcode Opcode = E->getOpcode();
8515 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8516 }
8517
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008518 assert((!LHSTy->isIntegralOrEnumerationType() ||
8519 !RHSTy->isIntegralOrEnumerationType()) &&
8520 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8521 // We can't continue from here for non-integral types.
8522 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008523}
8524
Peter Collingbournee190dee2011-03-11 19:24:49 +00008525/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8526/// a result as the expression's type.
8527bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8528 const UnaryExprOrTypeTraitExpr *E) {
8529 switch(E->getKind()) {
8530 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008531 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008532 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008533 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008534 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008535 }
Eli Friedman64004332009-03-23 04:38:34 +00008536
Peter Collingbournee190dee2011-03-11 19:24:49 +00008537 case UETT_VecStep: {
8538 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008539
Peter Collingbournee190dee2011-03-11 19:24:49 +00008540 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008541 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008542
Peter Collingbournee190dee2011-03-11 19:24:49 +00008543 // The vec_step built-in functions that take a 3-component
8544 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8545 if (n == 3)
8546 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008547
Peter Collingbournee190dee2011-03-11 19:24:49 +00008548 return Success(n, E);
8549 } else
8550 return Success(1, E);
8551 }
8552
8553 case UETT_SizeOf: {
8554 QualType SrcTy = E->getTypeOfArgument();
8555 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8556 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008557 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8558 SrcTy = Ref->getPointeeType();
8559
Richard Smithd62306a2011-11-10 06:34:14 +00008560 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008561 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008562 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008563 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008564 }
Alexey Bataev00396512015-07-02 03:40:19 +00008565 case UETT_OpenMPRequiredSimdAlign:
8566 assert(E->isArgumentType());
8567 return Success(
8568 Info.Ctx.toCharUnitsFromBits(
8569 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8570 .getQuantity(),
8571 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008572 }
8573
8574 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008575}
8576
Peter Collingbournee9200682011-05-13 03:29:01 +00008577bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008578 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008579 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008580 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008581 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008582 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008583 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008584 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008585 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008586 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008587 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008588 APSInt IdxResult;
8589 if (!EvaluateInteger(Idx, IdxResult, Info))
8590 return false;
8591 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8592 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008593 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008594 CurrentType = AT->getElementType();
8595 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8596 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008597 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008598 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008599
James Y Knight7281c352015-12-29 22:31:18 +00008600 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008601 FieldDecl *MemberDecl = ON.getField();
8602 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008603 if (!RT)
8604 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008605 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008606 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008607 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008608 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008609 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008610 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008611 CurrentType = MemberDecl->getType().getNonReferenceType();
8612 break;
8613 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008614
James Y Knight7281c352015-12-29 22:31:18 +00008615 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008616 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008617
James Y Knight7281c352015-12-29 22:31:18 +00008618 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008619 CXXBaseSpecifier *BaseSpec = ON.getBase();
8620 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008621 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008622
8623 // Find the layout of the class whose base we are looking into.
8624 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008625 if (!RT)
8626 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008627 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008628 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008629 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8630
8631 // Find the base class itself.
8632 CurrentType = BaseSpec->getType();
8633 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8634 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008635 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008636
8637 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008638 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008639 break;
8640 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008641 }
8642 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008643 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008644}
8645
Chris Lattnere13042c2008-07-11 19:10:17 +00008646bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008647 switch (E->getOpcode()) {
8648 default:
8649 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8650 // See C99 6.6p3.
8651 return Error(E);
8652 case UO_Extension:
8653 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8654 // If so, we could clear the diagnostic ID.
8655 return Visit(E->getSubExpr());
8656 case UO_Plus:
8657 // The result is just the value.
8658 return Visit(E->getSubExpr());
8659 case UO_Minus: {
8660 if (!Visit(E->getSubExpr()))
8661 return false;
8662 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008663 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008664 if (Value.isSigned() && Value.isMinSignedValue() &&
8665 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8666 E->getType()))
8667 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008668 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008669 }
8670 case UO_Not: {
8671 if (!Visit(E->getSubExpr()))
8672 return false;
8673 if (!Result.isInt()) return Error(E);
8674 return Success(~Result.getInt(), E);
8675 }
8676 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008677 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008678 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008679 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008680 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008681 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008682 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008683}
Mike Stump11289f42009-09-09 15:08:12 +00008684
Chris Lattner477c4be2008-07-12 01:15:53 +00008685/// HandleCast - This is used to evaluate implicit or explicit casts where the
8686/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008687bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8688 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008689 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008690 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008691
Eli Friedmanc757de22011-03-25 00:43:55 +00008692 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008693 case CK_BaseToDerived:
8694 case CK_DerivedToBase:
8695 case CK_UncheckedDerivedToBase:
8696 case CK_Dynamic:
8697 case CK_ToUnion:
8698 case CK_ArrayToPointerDecay:
8699 case CK_FunctionToPointerDecay:
8700 case CK_NullToPointer:
8701 case CK_NullToMemberPointer:
8702 case CK_BaseToDerivedMemberPointer:
8703 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008704 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008705 case CK_ConstructorConversion:
8706 case CK_IntegralToPointer:
8707 case CK_ToVoid:
8708 case CK_VectorSplat:
8709 case CK_IntegralToFloating:
8710 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008711 case CK_CPointerToObjCPointerCast:
8712 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008713 case CK_AnyPointerToBlockPointerCast:
8714 case CK_ObjCObjectLValueCast:
8715 case CK_FloatingRealToComplex:
8716 case CK_FloatingComplexToReal:
8717 case CK_FloatingComplexCast:
8718 case CK_FloatingComplexToIntegralComplex:
8719 case CK_IntegralRealToComplex:
8720 case CK_IntegralComplexCast:
8721 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008722 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008723 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008724 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008725 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008726 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008727 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008728 llvm_unreachable("invalid cast kind for integral value");
8729
Eli Friedman9faf2f92011-03-25 19:07:11 +00008730 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008731 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008732 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008733 case CK_ARCProduceObject:
8734 case CK_ARCConsumeObject:
8735 case CK_ARCReclaimReturnedObject:
8736 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008737 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008738 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008739
Richard Smith4ef685b2012-01-17 21:17:26 +00008740 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008741 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008742 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008743 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008744 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008745
8746 case CK_MemberPointerToBoolean:
8747 case CK_PointerToBoolean:
8748 case CK_IntegralToBoolean:
8749 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008750 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008751 case CK_FloatingComplexToBoolean:
8752 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008753 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008754 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008755 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008756 uint64_t IntResult = BoolResult;
8757 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8758 IntResult = (uint64_t)-1;
8759 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008760 }
8761
Eli Friedmanc757de22011-03-25 00:43:55 +00008762 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008763 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008764 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008765
Eli Friedman742421e2009-02-20 01:15:07 +00008766 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008767 // Allow casts of address-of-label differences if they are no-ops
8768 // or narrowing. (The narrowing case isn't actually guaranteed to
8769 // be constant-evaluatable except in some narrow cases which are hard
8770 // to detect here. We let it through on the assumption the user knows
8771 // what they are doing.)
8772 if (Result.isAddrLabelDiff())
8773 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008774 // Only allow casts of lvalues if they are lossless.
8775 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8776 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008777
Richard Smith911e1422012-01-30 22:27:01 +00008778 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8779 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008780 }
Mike Stump11289f42009-09-09 15:08:12 +00008781
Eli Friedmanc757de22011-03-25 00:43:55 +00008782 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008783 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8784
John McCall45d55e42010-05-07 21:00:08 +00008785 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008786 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008787 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008788
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008789 if (LV.getLValueBase()) {
8790 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008791 // FIXME: Allow a larger integer size than the pointer size, and allow
8792 // narrowing back down to pointer width in subsequent integral casts.
8793 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008794 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008795 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008796
Richard Smithcf74da72011-11-16 07:18:12 +00008797 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008798 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008799 return true;
8800 }
8801
Yaxun Liu402804b2016-12-15 08:09:08 +00008802 uint64_t V;
8803 if (LV.isNullPointer())
8804 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8805 else
8806 V = LV.getLValueOffset().getQuantity();
8807
8808 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008809 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008810 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008811
Eli Friedmanc757de22011-03-25 00:43:55 +00008812 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008813 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008814 if (!EvaluateComplex(SubExpr, C, Info))
8815 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008816 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008817 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008818
Eli Friedmanc757de22011-03-25 00:43:55 +00008819 case CK_FloatingToIntegral: {
8820 APFloat F(0.0);
8821 if (!EvaluateFloat(SubExpr, F, Info))
8822 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008823
Richard Smith357362d2011-12-13 06:39:58 +00008824 APSInt Value;
8825 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8826 return false;
8827 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008828 }
8829 }
Mike Stump11289f42009-09-09 15:08:12 +00008830
Eli Friedmanc757de22011-03-25 00:43:55 +00008831 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008832}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008833
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008834bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8835 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008836 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008837 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8838 return false;
8839 if (!LV.isComplexInt())
8840 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008841 return Success(LV.getComplexIntReal(), E);
8842 }
8843
8844 return Visit(E->getSubExpr());
8845}
8846
Eli Friedman4e7a2412009-02-27 04:45:43 +00008847bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008848 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008849 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008850 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8851 return false;
8852 if (!LV.isComplexInt())
8853 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008854 return Success(LV.getComplexIntImag(), E);
8855 }
8856
Richard Smith4a678122011-10-24 18:44:57 +00008857 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008858 return Success(0, E);
8859}
8860
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008861bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8862 return Success(E->getPackLength(), E);
8863}
8864
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008865bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8866 return Success(E->getValue(), E);
8867}
8868
Chris Lattner05706e882008-07-11 18:11:29 +00008869//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008870// Float Evaluation
8871//===----------------------------------------------------------------------===//
8872
8873namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008874class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008875 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008876 APFloat &Result;
8877public:
8878 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008879 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008880
Richard Smith2e312c82012-03-03 22:46:17 +00008881 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008882 Result = V.getFloat();
8883 return true;
8884 }
Eli Friedman24c01542008-08-22 00:06:13 +00008885
Richard Smithfddd3842011-12-30 21:15:51 +00008886 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008887 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8888 return true;
8889 }
8890
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008891 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008892
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008893 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008894 bool VisitBinaryOperator(const BinaryOperator *E);
8895 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008896 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008897
John McCallb1fb0d32010-05-07 22:08:54 +00008898 bool VisitUnaryReal(const UnaryOperator *E);
8899 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008900
Richard Smithfddd3842011-12-30 21:15:51 +00008901 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008902};
8903} // end anonymous namespace
8904
8905static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008906 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008907 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008908}
8909
Jay Foad39c79802011-01-12 09:06:06 +00008910static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008911 QualType ResultTy,
8912 const Expr *Arg,
8913 bool SNaN,
8914 llvm::APFloat &Result) {
8915 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8916 if (!S) return false;
8917
8918 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8919
8920 llvm::APInt fill;
8921
8922 // Treat empty strings as if they were zero.
8923 if (S->getString().empty())
8924 fill = llvm::APInt(32, 0);
8925 else if (S->getString().getAsInteger(0, fill))
8926 return false;
8927
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008928 if (Context.getTargetInfo().isNan2008()) {
8929 if (SNaN)
8930 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8931 else
8932 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8933 } else {
8934 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8935 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8936 // a different encoding to what became a standard in 2008, and for pre-
8937 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8938 // sNaN. This is now known as "legacy NaN" encoding.
8939 if (SNaN)
8940 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8941 else
8942 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8943 }
8944
John McCall16291492010-02-28 13:00:19 +00008945 return true;
8946}
8947
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008948bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008949 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008950 default:
8951 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8952
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008953 case Builtin::BI__builtin_huge_val:
8954 case Builtin::BI__builtin_huge_valf:
8955 case Builtin::BI__builtin_huge_vall:
8956 case Builtin::BI__builtin_inf:
8957 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008958 case Builtin::BI__builtin_infl: {
8959 const llvm::fltSemantics &Sem =
8960 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008961 Result = llvm::APFloat::getInf(Sem);
8962 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008963 }
Mike Stump11289f42009-09-09 15:08:12 +00008964
John McCall16291492010-02-28 13:00:19 +00008965 case Builtin::BI__builtin_nans:
8966 case Builtin::BI__builtin_nansf:
8967 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008968 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8969 true, Result))
8970 return Error(E);
8971 return true;
John McCall16291492010-02-28 13:00:19 +00008972
Chris Lattner0b7282e2008-10-06 06:31:58 +00008973 case Builtin::BI__builtin_nan:
8974 case Builtin::BI__builtin_nanf:
8975 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008976 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008977 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008978 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8979 false, Result))
8980 return Error(E);
8981 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008982
8983 case Builtin::BI__builtin_fabs:
8984 case Builtin::BI__builtin_fabsf:
8985 case Builtin::BI__builtin_fabsl:
8986 if (!EvaluateFloat(E->getArg(0), Result, Info))
8987 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008988
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008989 if (Result.isNegative())
8990 Result.changeSign();
8991 return true;
8992
Richard Smith8889a3d2013-06-13 06:26:32 +00008993 // FIXME: Builtin::BI__builtin_powi
8994 // FIXME: Builtin::BI__builtin_powif
8995 // FIXME: Builtin::BI__builtin_powil
8996
Mike Stump11289f42009-09-09 15:08:12 +00008997 case Builtin::BI__builtin_copysign:
8998 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008999 case Builtin::BI__builtin_copysignl: {
9000 APFloat RHS(0.);
9001 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9002 !EvaluateFloat(E->getArg(1), RHS, Info))
9003 return false;
9004 Result.copySign(RHS);
9005 return true;
9006 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009007 }
9008}
9009
John McCallb1fb0d32010-05-07 22:08:54 +00009010bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009011 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9012 ComplexValue CV;
9013 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9014 return false;
9015 Result = CV.FloatReal;
9016 return true;
9017 }
9018
9019 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009020}
9021
9022bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009023 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9024 ComplexValue CV;
9025 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9026 return false;
9027 Result = CV.FloatImag;
9028 return true;
9029 }
9030
Richard Smith4a678122011-10-24 18:44:57 +00009031 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009032 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9033 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009034 return true;
9035}
9036
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009037bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009038 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009039 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009040 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009041 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009042 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009043 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9044 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009045 Result.changeSign();
9046 return true;
9047 }
9048}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009049
Eli Friedman24c01542008-08-22 00:06:13 +00009050bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009051 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9052 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009053
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009054 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009055 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009056 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009057 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009058 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9059 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009060}
9061
9062bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9063 Result = E->getValue();
9064 return true;
9065}
9066
Peter Collingbournee9200682011-05-13 03:29:01 +00009067bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9068 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009069
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009070 switch (E->getCastKind()) {
9071 default:
Richard Smith11562c52011-10-28 17:51:58 +00009072 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009073
9074 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009075 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009076 return EvaluateInteger(SubExpr, IntResult, Info) &&
9077 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9078 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009079 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009080
9081 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009082 if (!Visit(SubExpr))
9083 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009084 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9085 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009086 }
John McCalld7646252010-11-14 08:17:51 +00009087
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009088 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009089 ComplexValue V;
9090 if (!EvaluateComplex(SubExpr, V, Info))
9091 return false;
9092 Result = V.getComplexFloatReal();
9093 return true;
9094 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009095 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009096}
9097
Eli Friedman24c01542008-08-22 00:06:13 +00009098//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009099// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009100//===----------------------------------------------------------------------===//
9101
9102namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009103class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009104 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009105 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009106
Anders Carlsson537969c2008-11-16 20:27:53 +00009107public:
John McCall93d91dc2010-05-07 17:22:02 +00009108 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009109 : ExprEvaluatorBaseTy(info), Result(Result) {}
9110
Richard Smith2e312c82012-03-03 22:46:17 +00009111 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009112 Result.setFrom(V);
9113 return true;
9114 }
Mike Stump11289f42009-09-09 15:08:12 +00009115
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009116 bool ZeroInitialization(const Expr *E);
9117
Anders Carlsson537969c2008-11-16 20:27:53 +00009118 //===--------------------------------------------------------------------===//
9119 // Visitor Methods
9120 //===--------------------------------------------------------------------===//
9121
Peter Collingbournee9200682011-05-13 03:29:01 +00009122 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009123 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009124 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009125 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009126 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009127};
9128} // end anonymous namespace
9129
John McCall93d91dc2010-05-07 17:22:02 +00009130static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9131 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009132 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009133 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009134}
9135
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009136bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009137 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009138 if (ElemTy->isRealFloatingType()) {
9139 Result.makeComplexFloat();
9140 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9141 Result.FloatReal = Zero;
9142 Result.FloatImag = Zero;
9143 } else {
9144 Result.makeComplexInt();
9145 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9146 Result.IntReal = Zero;
9147 Result.IntImag = Zero;
9148 }
9149 return true;
9150}
9151
Peter Collingbournee9200682011-05-13 03:29:01 +00009152bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9153 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009154
9155 if (SubExpr->getType()->isRealFloatingType()) {
9156 Result.makeComplexFloat();
9157 APFloat &Imag = Result.FloatImag;
9158 if (!EvaluateFloat(SubExpr, Imag, Info))
9159 return false;
9160
9161 Result.FloatReal = APFloat(Imag.getSemantics());
9162 return true;
9163 } else {
9164 assert(SubExpr->getType()->isIntegerType() &&
9165 "Unexpected imaginary literal.");
9166
9167 Result.makeComplexInt();
9168 APSInt &Imag = Result.IntImag;
9169 if (!EvaluateInteger(SubExpr, Imag, Info))
9170 return false;
9171
9172 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9173 return true;
9174 }
9175}
9176
Peter Collingbournee9200682011-05-13 03:29:01 +00009177bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009178
John McCallfcef3cf2010-12-14 17:51:41 +00009179 switch (E->getCastKind()) {
9180 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009181 case CK_BaseToDerived:
9182 case CK_DerivedToBase:
9183 case CK_UncheckedDerivedToBase:
9184 case CK_Dynamic:
9185 case CK_ToUnion:
9186 case CK_ArrayToPointerDecay:
9187 case CK_FunctionToPointerDecay:
9188 case CK_NullToPointer:
9189 case CK_NullToMemberPointer:
9190 case CK_BaseToDerivedMemberPointer:
9191 case CK_DerivedToBaseMemberPointer:
9192 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009193 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009194 case CK_ConstructorConversion:
9195 case CK_IntegralToPointer:
9196 case CK_PointerToIntegral:
9197 case CK_PointerToBoolean:
9198 case CK_ToVoid:
9199 case CK_VectorSplat:
9200 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009201 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009202 case CK_IntegralToBoolean:
9203 case CK_IntegralToFloating:
9204 case CK_FloatingToIntegral:
9205 case CK_FloatingToBoolean:
9206 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009207 case CK_CPointerToObjCPointerCast:
9208 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009209 case CK_AnyPointerToBlockPointerCast:
9210 case CK_ObjCObjectLValueCast:
9211 case CK_FloatingComplexToReal:
9212 case CK_FloatingComplexToBoolean:
9213 case CK_IntegralComplexToReal:
9214 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009215 case CK_ARCProduceObject:
9216 case CK_ARCConsumeObject:
9217 case CK_ARCReclaimReturnedObject:
9218 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009219 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009220 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009221 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009222 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009223 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009224 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009225 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009226 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009227
John McCallfcef3cf2010-12-14 17:51:41 +00009228 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009229 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009230 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009231 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009232
9233 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009234 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009235 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009236 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009237
9238 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009239 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009240 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009241 return false;
9242
John McCallfcef3cf2010-12-14 17:51:41 +00009243 Result.makeComplexFloat();
9244 Result.FloatImag = APFloat(Real.getSemantics());
9245 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009246 }
9247
John McCallfcef3cf2010-12-14 17:51:41 +00009248 case CK_FloatingComplexCast: {
9249 if (!Visit(E->getSubExpr()))
9250 return false;
9251
9252 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9253 QualType From
9254 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9255
Richard Smith357362d2011-12-13 06:39:58 +00009256 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9257 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009258 }
9259
9260 case CK_FloatingComplexToIntegralComplex: {
9261 if (!Visit(E->getSubExpr()))
9262 return false;
9263
9264 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9265 QualType From
9266 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9267 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009268 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9269 To, Result.IntReal) &&
9270 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9271 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009272 }
9273
9274 case CK_IntegralRealToComplex: {
9275 APSInt &Real = Result.IntReal;
9276 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9277 return false;
9278
9279 Result.makeComplexInt();
9280 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9281 return true;
9282 }
9283
9284 case CK_IntegralComplexCast: {
9285 if (!Visit(E->getSubExpr()))
9286 return false;
9287
9288 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9289 QualType From
9290 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9291
Richard Smith911e1422012-01-30 22:27:01 +00009292 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9293 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009294 return true;
9295 }
9296
9297 case CK_IntegralComplexToFloatingComplex: {
9298 if (!Visit(E->getSubExpr()))
9299 return false;
9300
Ted Kremenek28831752012-08-23 20:46:57 +00009301 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009302 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009303 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009304 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009305 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9306 To, Result.FloatReal) &&
9307 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9308 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009309 }
9310 }
9311
9312 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009313}
9314
John McCall93d91dc2010-05-07 17:22:02 +00009315bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009316 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009317 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9318
Chandler Carrutha216cad2014-10-11 00:57:18 +00009319 // Track whether the LHS or RHS is real at the type system level. When this is
9320 // the case we can simplify our evaluation strategy.
9321 bool LHSReal = false, RHSReal = false;
9322
9323 bool LHSOK;
9324 if (E->getLHS()->getType()->isRealFloatingType()) {
9325 LHSReal = true;
9326 APFloat &Real = Result.FloatReal;
9327 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9328 if (LHSOK) {
9329 Result.makeComplexFloat();
9330 Result.FloatImag = APFloat(Real.getSemantics());
9331 }
9332 } else {
9333 LHSOK = Visit(E->getLHS());
9334 }
George Burgess IVa145e252016-05-25 22:38:36 +00009335 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009336 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009337
John McCall93d91dc2010-05-07 17:22:02 +00009338 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009339 if (E->getRHS()->getType()->isRealFloatingType()) {
9340 RHSReal = true;
9341 APFloat &Real = RHS.FloatReal;
9342 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9343 return false;
9344 RHS.makeComplexFloat();
9345 RHS.FloatImag = APFloat(Real.getSemantics());
9346 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009347 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009348
Chandler Carrutha216cad2014-10-11 00:57:18 +00009349 assert(!(LHSReal && RHSReal) &&
9350 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009351 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009352 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009353 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009354 if (Result.isComplexFloat()) {
9355 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9356 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009357 if (LHSReal)
9358 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9359 else if (!RHSReal)
9360 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9361 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009362 } else {
9363 Result.getComplexIntReal() += RHS.getComplexIntReal();
9364 Result.getComplexIntImag() += RHS.getComplexIntImag();
9365 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009366 break;
John McCalle3027922010-08-25 11:45:40 +00009367 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009368 if (Result.isComplexFloat()) {
9369 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9370 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009371 if (LHSReal) {
9372 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9373 Result.getComplexFloatImag().changeSign();
9374 } else if (!RHSReal) {
9375 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9376 APFloat::rmNearestTiesToEven);
9377 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009378 } else {
9379 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9380 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9381 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009382 break;
John McCalle3027922010-08-25 11:45:40 +00009383 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009384 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009385 // This is an implementation of complex multiplication according to the
9386 // constraints laid out in C11 Annex G. The implemantion uses the
9387 // following naming scheme:
9388 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009389 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009390 APFloat &A = LHS.getComplexFloatReal();
9391 APFloat &B = LHS.getComplexFloatImag();
9392 APFloat &C = RHS.getComplexFloatReal();
9393 APFloat &D = RHS.getComplexFloatImag();
9394 APFloat &ResR = Result.getComplexFloatReal();
9395 APFloat &ResI = Result.getComplexFloatImag();
9396 if (LHSReal) {
9397 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9398 ResR = A * C;
9399 ResI = A * D;
9400 } else if (RHSReal) {
9401 ResR = C * A;
9402 ResI = C * B;
9403 } else {
9404 // In the fully general case, we need to handle NaNs and infinities
9405 // robustly.
9406 APFloat AC = A * C;
9407 APFloat BD = B * D;
9408 APFloat AD = A * D;
9409 APFloat BC = B * C;
9410 ResR = AC - BD;
9411 ResI = AD + BC;
9412 if (ResR.isNaN() && ResI.isNaN()) {
9413 bool Recalc = false;
9414 if (A.isInfinity() || B.isInfinity()) {
9415 A = APFloat::copySign(
9416 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9417 B = APFloat::copySign(
9418 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9419 if (C.isNaN())
9420 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9421 if (D.isNaN())
9422 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9423 Recalc = true;
9424 }
9425 if (C.isInfinity() || D.isInfinity()) {
9426 C = APFloat::copySign(
9427 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9428 D = APFloat::copySign(
9429 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9430 if (A.isNaN())
9431 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9432 if (B.isNaN())
9433 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9434 Recalc = true;
9435 }
9436 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9437 AD.isInfinity() || BC.isInfinity())) {
9438 if (A.isNaN())
9439 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9440 if (B.isNaN())
9441 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9442 if (C.isNaN())
9443 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9444 if (D.isNaN())
9445 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9446 Recalc = true;
9447 }
9448 if (Recalc) {
9449 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9450 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9451 }
9452 }
9453 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009454 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009455 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009456 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009457 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9458 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009459 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009460 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9461 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9462 }
9463 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009464 case BO_Div:
9465 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009466 // This is an implementation of complex division according to the
9467 // constraints laid out in C11 Annex G. The implemantion uses the
9468 // following naming scheme:
9469 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009470 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009471 APFloat &A = LHS.getComplexFloatReal();
9472 APFloat &B = LHS.getComplexFloatImag();
9473 APFloat &C = RHS.getComplexFloatReal();
9474 APFloat &D = RHS.getComplexFloatImag();
9475 APFloat &ResR = Result.getComplexFloatReal();
9476 APFloat &ResI = Result.getComplexFloatImag();
9477 if (RHSReal) {
9478 ResR = A / C;
9479 ResI = B / C;
9480 } else {
9481 if (LHSReal) {
9482 // No real optimizations we can do here, stub out with zero.
9483 B = APFloat::getZero(A.getSemantics());
9484 }
9485 int DenomLogB = 0;
9486 APFloat MaxCD = maxnum(abs(C), abs(D));
9487 if (MaxCD.isFinite()) {
9488 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009489 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9490 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009491 }
9492 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009493 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9494 APFloat::rmNearestTiesToEven);
9495 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9496 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009497 if (ResR.isNaN() && ResI.isNaN()) {
9498 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9499 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9500 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9501 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9502 D.isFinite()) {
9503 A = APFloat::copySign(
9504 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9505 B = APFloat::copySign(
9506 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9507 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9508 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9509 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9510 C = APFloat::copySign(
9511 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9512 D = APFloat::copySign(
9513 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9514 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9515 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9516 }
9517 }
9518 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009519 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009520 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9521 return Error(E, diag::note_expr_divide_by_zero);
9522
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009523 ComplexValue LHS = Result;
9524 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9525 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9526 Result.getComplexIntReal() =
9527 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9528 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9529 Result.getComplexIntImag() =
9530 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9531 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9532 }
9533 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009534 }
9535
John McCall93d91dc2010-05-07 17:22:02 +00009536 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009537}
9538
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009539bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9540 // Get the operand value into 'Result'.
9541 if (!Visit(E->getSubExpr()))
9542 return false;
9543
9544 switch (E->getOpcode()) {
9545 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009546 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009547 case UO_Extension:
9548 return true;
9549 case UO_Plus:
9550 // The result is always just the subexpr.
9551 return true;
9552 case UO_Minus:
9553 if (Result.isComplexFloat()) {
9554 Result.getComplexFloatReal().changeSign();
9555 Result.getComplexFloatImag().changeSign();
9556 }
9557 else {
9558 Result.getComplexIntReal() = -Result.getComplexIntReal();
9559 Result.getComplexIntImag() = -Result.getComplexIntImag();
9560 }
9561 return true;
9562 case UO_Not:
9563 if (Result.isComplexFloat())
9564 Result.getComplexFloatImag().changeSign();
9565 else
9566 Result.getComplexIntImag() = -Result.getComplexIntImag();
9567 return true;
9568 }
9569}
9570
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009571bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9572 if (E->getNumInits() == 2) {
9573 if (E->getType()->isComplexType()) {
9574 Result.makeComplexFloat();
9575 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9576 return false;
9577 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9578 return false;
9579 } else {
9580 Result.makeComplexInt();
9581 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9582 return false;
9583 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9584 return false;
9585 }
9586 return true;
9587 }
9588 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9589}
9590
Anders Carlsson537969c2008-11-16 20:27:53 +00009591//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009592// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9593// implicit conversion.
9594//===----------------------------------------------------------------------===//
9595
9596namespace {
9597class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009598 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00009599 APValue &Result;
9600public:
9601 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
9602 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9603
9604 bool Success(const APValue &V, const Expr *E) {
9605 Result = V;
9606 return true;
9607 }
9608
9609 bool ZeroInitialization(const Expr *E) {
9610 ImplicitValueInitExpr VIE(
9611 E->getType()->castAs<AtomicType>()->getValueType());
9612 return Evaluate(Result, Info, &VIE);
9613 }
9614
9615 bool VisitCastExpr(const CastExpr *E) {
9616 switch (E->getCastKind()) {
9617 default:
9618 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9619 case CK_NonAtomicToAtomic:
9620 return Evaluate(Result, Info, E->getSubExpr());
9621 }
9622 }
9623};
9624} // end anonymous namespace
9625
9626static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
9627 assert(E->isRValue() && E->getType()->isAtomicType());
9628 return AtomicExprEvaluator(Info, Result).Visit(E);
9629}
9630
9631//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009632// Void expression evaluation, primarily for a cast to void on the LHS of a
9633// comma operator
9634//===----------------------------------------------------------------------===//
9635
9636namespace {
9637class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009638 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009639public:
9640 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9641
Richard Smith2e312c82012-03-03 22:46:17 +00009642 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009643
9644 bool VisitCastExpr(const CastExpr *E) {
9645 switch (E->getCastKind()) {
9646 default:
9647 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9648 case CK_ToVoid:
9649 VisitIgnoredValue(E->getSubExpr());
9650 return true;
9651 }
9652 }
Hal Finkela8443c32014-07-17 14:49:58 +00009653
9654 bool VisitCallExpr(const CallExpr *E) {
9655 switch (E->getBuiltinCallee()) {
9656 default:
9657 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9658 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009659 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009660 // The argument is not evaluated!
9661 return true;
9662 }
9663 }
Richard Smith42d3af92011-12-07 00:43:50 +00009664};
9665} // end anonymous namespace
9666
9667static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9668 assert(E->isRValue() && E->getType()->isVoidType());
9669 return VoidExprEvaluator(Info).Visit(E);
9670}
9671
9672//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009673// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009674//===----------------------------------------------------------------------===//
9675
Richard Smith2e312c82012-03-03 22:46:17 +00009676static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009677 // In C, function designators are not lvalues, but we evaluate them as if they
9678 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009679 QualType T = E->getType();
9680 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009681 LValue LV;
9682 if (!EvaluateLValue(E, LV, Info))
9683 return false;
9684 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009685 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009686 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009687 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009688 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009689 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009690 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009691 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009692 LValue LV;
9693 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009694 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009695 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009696 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009697 llvm::APFloat F(0.0);
9698 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009699 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009700 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009701 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009702 ComplexValue C;
9703 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009704 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009705 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009706 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009707 MemberPtr P;
9708 if (!EvaluateMemberPointer(E, P, Info))
9709 return false;
9710 P.moveInto(Result);
9711 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009712 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009713 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009714 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009715 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9716 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009717 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009718 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009719 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009720 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009721 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009722 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9723 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009724 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009725 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009726 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009727 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009728 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009729 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009730 if (!EvaluateVoid(E, Info))
9731 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009732 } else if (T->isAtomicType()) {
9733 if (!EvaluateAtomic(E, Result, Info))
9734 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009735 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009736 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009737 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009738 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009739 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009740 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009741 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009742
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009743 return true;
9744}
9745
Richard Smithb228a862012-02-15 02:18:13 +00009746/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9747/// cases, the in-place evaluation is essential, since later initializers for
9748/// an object can indirectly refer to subobjects which were initialized earlier.
9749static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009750 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009751 assert(!E->isValueDependent());
9752
Richard Smith7525ff62013-05-09 07:14:00 +00009753 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009754 return false;
9755
9756 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009757 // Evaluate arrays and record types in-place, so that later initializers can
9758 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00009759 if (E->getType()->isArrayType())
9760 return EvaluateArray(E, This, Result, Info);
9761 else if (E->getType()->isRecordType())
9762 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00009763 }
9764
9765 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009766 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009767}
9768
Richard Smithf57d8cb2011-12-09 22:58:01 +00009769/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9770/// lvalue-to-rvalue cast if it is an lvalue.
9771static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009772 if (E->getType().isNull())
9773 return false;
9774
Richard Smithfddd3842011-12-30 21:15:51 +00009775 if (!CheckLiteralType(Info, E))
9776 return false;
9777
Richard Smith2e312c82012-03-03 22:46:17 +00009778 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009779 return false;
9780
9781 if (E->isGLValue()) {
9782 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009783 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009784 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009785 return false;
9786 }
9787
Richard Smith2e312c82012-03-03 22:46:17 +00009788 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009789 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009790}
Richard Smith11562c52011-10-28 17:51:58 +00009791
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009792static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9793 const ASTContext &Ctx, bool &IsConst) {
9794 // Fast-path evaluations of integer literals, since we sometimes see files
9795 // containing vast quantities of these.
9796 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9797 Result.Val = APValue(APSInt(L->getValue(),
9798 L->getType()->isUnsignedIntegerType()));
9799 IsConst = true;
9800 return true;
9801 }
James Dennett0492ef02014-03-14 17:44:10 +00009802
9803 // This case should be rare, but we need to check it before we check on
9804 // the type below.
9805 if (Exp->getType().isNull()) {
9806 IsConst = false;
9807 return true;
9808 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009809
9810 // FIXME: Evaluating values of large array and record types can cause
9811 // performance problems. Only do so in C++11 for now.
9812 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9813 Exp->getType()->isRecordType()) &&
9814 !Ctx.getLangOpts().CPlusPlus11) {
9815 IsConst = false;
9816 return true;
9817 }
9818 return false;
9819}
9820
9821
Richard Smith7b553f12011-10-29 00:50:52 +00009822/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009823/// any crazy technique (that has nothing to do with language standards) that
9824/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009825/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9826/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009827bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009828 bool IsConst;
9829 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9830 return IsConst;
9831
Richard Smith6d4c6582013-11-05 22:18:15 +00009832 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009833 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009834}
9835
Jay Foad39c79802011-01-12 09:06:06 +00009836bool Expr::EvaluateAsBooleanCondition(bool &Result,
9837 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009838 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009839 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009840 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009841}
9842
Richard Smithce8eca52015-12-08 03:21:47 +00009843static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9844 Expr::SideEffectsKind SEK) {
9845 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9846 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9847}
9848
Richard Smith5fab0c92011-12-28 19:48:30 +00009849bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9850 SideEffectsKind AllowSideEffects) const {
9851 if (!getType()->isIntegralOrEnumerationType())
9852 return false;
9853
Richard Smith11562c52011-10-28 17:51:58 +00009854 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009855 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009856 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009857 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009858
Richard Smith11562c52011-10-28 17:51:58 +00009859 Result = ExprResult.Val.getInt();
9860 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009861}
9862
Richard Trieube234c32016-04-21 21:04:55 +00009863bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9864 SideEffectsKind AllowSideEffects) const {
9865 if (!getType()->isRealFloatingType())
9866 return false;
9867
9868 EvalResult ExprResult;
9869 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9870 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9871 return false;
9872
9873 Result = ExprResult.Val.getFloat();
9874 return true;
9875}
9876
Jay Foad39c79802011-01-12 09:06:06 +00009877bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009878 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009879
John McCall45d55e42010-05-07 21:00:08 +00009880 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009881 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9882 !CheckLValueConstantExpression(Info, getExprLoc(),
9883 Ctx.getLValueReferenceType(getType()), LV))
9884 return false;
9885
Richard Smith2e312c82012-03-03 22:46:17 +00009886 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009887 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009888}
9889
Richard Smithd0b4dd62011-12-19 06:19:21 +00009890bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9891 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009892 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009893 // FIXME: Evaluating initializers for large array and record types can cause
9894 // performance problems. Only do so in C++11 for now.
9895 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009896 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009897 return false;
9898
Richard Smithd0b4dd62011-12-19 06:19:21 +00009899 Expr::EvalStatus EStatus;
9900 EStatus.Diag = &Notes;
9901
Richard Smith0c6124b2015-12-03 01:36:22 +00009902 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9903 ? EvalInfo::EM_ConstantExpression
9904 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009905 InitInfo.setEvaluatingDecl(VD, Value);
9906
9907 LValue LVal;
9908 LVal.set(VD);
9909
Richard Smithfddd3842011-12-30 21:15:51 +00009910 // C++11 [basic.start.init]p2:
9911 // Variables with static storage duration or thread storage duration shall be
9912 // zero-initialized before any other initialization takes place.
9913 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009914 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009915 !VD->getType()->isReferenceType()) {
9916 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009917 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009918 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009919 return false;
9920 }
9921
Richard Smith7525ff62013-05-09 07:14:00 +00009922 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9923 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009924 EStatus.HasSideEffects)
9925 return false;
9926
9927 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9928 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009929}
9930
Richard Smith7b553f12011-10-29 00:50:52 +00009931/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9932/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009933bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009934 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009935 return EvaluateAsRValue(Result, Ctx) &&
9936 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009937}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009938
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009939APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009940 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009941 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009942 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009943 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009944 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009945 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009946 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009947
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009948 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009949}
John McCall864e3962010-05-07 05:32:02 +00009950
Richard Smithe9ff7702013-11-05 22:23:30 +00009951void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009952 bool IsConst;
9953 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009954 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009955 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009956 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9957 }
9958}
9959
Richard Smithe6c01442013-06-05 00:46:14 +00009960bool Expr::EvalResult::isGlobalLValue() const {
9961 assert(Val.isLValue());
9962 return IsGlobalLValue(Val.getLValueBase());
9963}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009964
9965
John McCall864e3962010-05-07 05:32:02 +00009966/// isIntegerConstantExpr - this recursive routine will test if an expression is
9967/// an integer constant expression.
9968
9969/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9970/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009971
9972// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009973// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9974// and a (possibly null) SourceLocation indicating the location of the problem.
9975//
John McCall864e3962010-05-07 05:32:02 +00009976// Note that to reduce code duplication, this helper does no evaluation
9977// itself; the caller checks whether the expression is evaluatable, and
9978// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +00009979// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +00009980
Dan Gohman28ade552010-07-26 21:25:24 +00009981namespace {
9982
Richard Smith9e575da2012-12-28 13:25:52 +00009983enum ICEKind {
9984 /// This expression is an ICE.
9985 IK_ICE,
9986 /// This expression is not an ICE, but if it isn't evaluated, it's
9987 /// a legal subexpression for an ICE. This return value is used to handle
9988 /// the comma operator in C99 mode, and non-constant subexpressions.
9989 IK_ICEIfUnevaluated,
9990 /// This expression is not an ICE, and is not a legal subexpression for one.
9991 IK_NotICE
9992};
9993
John McCall864e3962010-05-07 05:32:02 +00009994struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009995 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009996 SourceLocation Loc;
9997
Richard Smith9e575da2012-12-28 13:25:52 +00009998 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009999};
10000
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010001}
Dan Gohman28ade552010-07-26 21:25:24 +000010002
Richard Smith9e575da2012-12-28 13:25:52 +000010003static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10004
10005static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010006
Craig Toppera31a8822013-08-22 07:09:37 +000010007static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010008 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010009 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010010 !EVResult.Val.isInt())
10011 return ICEDiag(IK_NotICE, E->getLocStart());
10012
John McCall864e3962010-05-07 05:32:02 +000010013 return NoDiag();
10014}
10015
Craig Toppera31a8822013-08-22 07:09:37 +000010016static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010017 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010018 if (!E->getType()->isIntegralOrEnumerationType())
10019 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010020
10021 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010022#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010023#define STMT(Node, Base) case Expr::Node##Class:
10024#define EXPR(Node, Base)
10025#include "clang/AST/StmtNodes.inc"
10026 case Expr::PredefinedExprClass:
10027 case Expr::FloatingLiteralClass:
10028 case Expr::ImaginaryLiteralClass:
10029 case Expr::StringLiteralClass:
10030 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010031 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010032 case Expr::MemberExprClass:
10033 case Expr::CompoundAssignOperatorClass:
10034 case Expr::CompoundLiteralExprClass:
10035 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010036 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010037 case Expr::ArrayInitLoopExprClass:
10038 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010039 case Expr::NoInitExprClass:
10040 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010041 case Expr::ImplicitValueInitExprClass:
10042 case Expr::ParenListExprClass:
10043 case Expr::VAArgExprClass:
10044 case Expr::AddrLabelExprClass:
10045 case Expr::StmtExprClass:
10046 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010047 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010048 case Expr::CXXDynamicCastExprClass:
10049 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010050 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010051 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010052 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010053 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010054 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010055 case Expr::CXXThisExprClass:
10056 case Expr::CXXThrowExprClass:
10057 case Expr::CXXNewExprClass:
10058 case Expr::CXXDeleteExprClass:
10059 case Expr::CXXPseudoDestructorExprClass:
10060 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010061 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010062 case Expr::DependentScopeDeclRefExprClass:
10063 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010064 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010065 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010066 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010067 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010068 case Expr::CXXTemporaryObjectExprClass:
10069 case Expr::CXXUnresolvedConstructExprClass:
10070 case Expr::CXXDependentScopeMemberExprClass:
10071 case Expr::UnresolvedMemberExprClass:
10072 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010073 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010074 case Expr::ObjCArrayLiteralClass:
10075 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010076 case Expr::ObjCEncodeExprClass:
10077 case Expr::ObjCMessageExprClass:
10078 case Expr::ObjCSelectorExprClass:
10079 case Expr::ObjCProtocolExprClass:
10080 case Expr::ObjCIvarRefExprClass:
10081 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010082 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010083 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010084 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010085 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010086 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010087 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010088 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010089 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010090 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010091 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010092 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010093 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010094 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010095 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010096 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010097 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010098 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010099 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010100 case Expr::CoawaitExprClass:
10101 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010102 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010103
Richard Smithf137f932014-01-25 20:50:08 +000010104 case Expr::InitListExprClass: {
10105 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10106 // form "T x = { a };" is equivalent to "T x = a;".
10107 // Unless we're initializing a reference, T is a scalar as it is known to be
10108 // of integral or enumeration type.
10109 if (E->isRValue())
10110 if (cast<InitListExpr>(E)->getNumInits() == 1)
10111 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10112 return ICEDiag(IK_NotICE, E->getLocStart());
10113 }
10114
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010115 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010116 case Expr::GNUNullExprClass:
10117 // GCC considers the GNU __null value to be an integral constant expression.
10118 return NoDiag();
10119
John McCall7c454bb2011-07-15 05:09:51 +000010120 case Expr::SubstNonTypeTemplateParmExprClass:
10121 return
10122 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10123
John McCall864e3962010-05-07 05:32:02 +000010124 case Expr::ParenExprClass:
10125 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010126 case Expr::GenericSelectionExprClass:
10127 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010128 case Expr::IntegerLiteralClass:
10129 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010130 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010131 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010132 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010133 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010134 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010135 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010136 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010137 return NoDiag();
10138 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010139 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010140 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10141 // constant expressions, but they can never be ICEs because an ICE cannot
10142 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010143 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010144 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010145 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010146 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010147 }
Richard Smith6365c912012-02-24 22:12:32 +000010148 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010149 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10150 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010151 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010152 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010153 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010154 // Parameter variables are never constants. Without this check,
10155 // getAnyInitializer() can find a default argument, which leads
10156 // to chaos.
10157 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010158 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010159
10160 // C++ 7.1.5.1p2
10161 // A variable of non-volatile const-qualified integral or enumeration
10162 // type initialized by an ICE can be used in ICEs.
10163 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010164 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010165 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010166
Richard Smithd0b4dd62011-12-19 06:19:21 +000010167 const VarDecl *VD;
10168 // Look for a declaration of this variable that has an initializer, and
10169 // check whether it is an ICE.
10170 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10171 return NoDiag();
10172 else
Richard Smith9e575da2012-12-28 13:25:52 +000010173 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010174 }
10175 }
Richard Smith9e575da2012-12-28 13:25:52 +000010176 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010177 }
John McCall864e3962010-05-07 05:32:02 +000010178 case Expr::UnaryOperatorClass: {
10179 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10180 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010181 case UO_PostInc:
10182 case UO_PostDec:
10183 case UO_PreInc:
10184 case UO_PreDec:
10185 case UO_AddrOf:
10186 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010187 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010188 // C99 6.6/3 allows increment and decrement within unevaluated
10189 // subexpressions of constant expressions, but they can never be ICEs
10190 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010191 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010192 case UO_Extension:
10193 case UO_LNot:
10194 case UO_Plus:
10195 case UO_Minus:
10196 case UO_Not:
10197 case UO_Real:
10198 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010199 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010200 }
Richard Smith9e575da2012-12-28 13:25:52 +000010201
John McCall864e3962010-05-07 05:32:02 +000010202 // OffsetOf falls through here.
10203 }
10204 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010205 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10206 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10207 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10208 // compliance: we should warn earlier for offsetof expressions with
10209 // array subscripts that aren't ICEs, and if the array subscripts
10210 // are ICEs, the value of the offsetof must be an integer constant.
10211 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010212 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010213 case Expr::UnaryExprOrTypeTraitExprClass: {
10214 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10215 if ((Exp->getKind() == UETT_SizeOf) &&
10216 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010217 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010218 return NoDiag();
10219 }
10220 case Expr::BinaryOperatorClass: {
10221 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10222 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010223 case BO_PtrMemD:
10224 case BO_PtrMemI:
10225 case BO_Assign:
10226 case BO_MulAssign:
10227 case BO_DivAssign:
10228 case BO_RemAssign:
10229 case BO_AddAssign:
10230 case BO_SubAssign:
10231 case BO_ShlAssign:
10232 case BO_ShrAssign:
10233 case BO_AndAssign:
10234 case BO_XorAssign:
10235 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000010236 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10237 // constant expressions, but they can never be ICEs because an ICE cannot
10238 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010239 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010240
John McCalle3027922010-08-25 11:45:40 +000010241 case BO_Mul:
10242 case BO_Div:
10243 case BO_Rem:
10244 case BO_Add:
10245 case BO_Sub:
10246 case BO_Shl:
10247 case BO_Shr:
10248 case BO_LT:
10249 case BO_GT:
10250 case BO_LE:
10251 case BO_GE:
10252 case BO_EQ:
10253 case BO_NE:
10254 case BO_And:
10255 case BO_Xor:
10256 case BO_Or:
10257 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010258 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10259 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010260 if (Exp->getOpcode() == BO_Div ||
10261 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010262 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010263 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010264 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010265 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010266 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010267 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010268 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010269 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010270 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010271 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010272 }
10273 }
10274 }
John McCalle3027922010-08-25 11:45:40 +000010275 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010276 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010277 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10278 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010279 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10280 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010281 } else {
10282 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010283 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010284 }
10285 }
Richard Smith9e575da2012-12-28 13:25:52 +000010286 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010287 }
John McCalle3027922010-08-25 11:45:40 +000010288 case BO_LAnd:
10289 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010290 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10291 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010292 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010293 // Rare case where the RHS has a comma "side-effect"; we need
10294 // to actually check the condition to see whether the side
10295 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010296 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010297 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010298 return RHSResult;
10299 return NoDiag();
10300 }
10301
Richard Smith9e575da2012-12-28 13:25:52 +000010302 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010303 }
10304 }
10305 }
10306 case Expr::ImplicitCastExprClass:
10307 case Expr::CStyleCastExprClass:
10308 case Expr::CXXFunctionalCastExprClass:
10309 case Expr::CXXStaticCastExprClass:
10310 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010311 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010312 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010313 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010314 if (isa<ExplicitCastExpr>(E)) {
10315 if (const FloatingLiteral *FL
10316 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10317 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10318 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10319 APSInt IgnoredVal(DestWidth, !DestSigned);
10320 bool Ignored;
10321 // If the value does not fit in the destination type, the behavior is
10322 // undefined, so we are not required to treat it as a constant
10323 // expression.
10324 if (FL->getValue().convertToInteger(IgnoredVal,
10325 llvm::APFloat::rmTowardZero,
10326 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010327 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010328 return NoDiag();
10329 }
10330 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010331 switch (cast<CastExpr>(E)->getCastKind()) {
10332 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010333 case CK_AtomicToNonAtomic:
10334 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010335 case CK_NoOp:
10336 case CK_IntegralToBoolean:
10337 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010338 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010339 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010340 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010341 }
John McCall864e3962010-05-07 05:32:02 +000010342 }
John McCallc07a0c72011-02-17 10:25:35 +000010343 case Expr::BinaryConditionalOperatorClass: {
10344 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10345 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010346 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010347 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010348 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10349 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10350 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010351 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010352 return FalseResult;
10353 }
John McCall864e3962010-05-07 05:32:02 +000010354 case Expr::ConditionalOperatorClass: {
10355 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10356 // If the condition (ignoring parens) is a __builtin_constant_p call,
10357 // then only the true side is actually considered in an integer constant
10358 // expression, and it is fully evaluated. This is an important GNU
10359 // extension. See GCC PR38377 for discussion.
10360 if (const CallExpr *CallCE
10361 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010362 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010363 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010364 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010365 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010366 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010367
Richard Smithf57d8cb2011-12-09 22:58:01 +000010368 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10369 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010370
Richard Smith9e575da2012-12-28 13:25:52 +000010371 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010372 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010373 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010374 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010375 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010376 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010377 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010378 return NoDiag();
10379 // Rare case where the diagnostics depend on which side is evaluated
10380 // Note that if we get here, CondResult is 0, and at least one of
10381 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010382 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010383 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010384 return TrueResult;
10385 }
10386 case Expr::CXXDefaultArgExprClass:
10387 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010388 case Expr::CXXDefaultInitExprClass:
10389 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010390 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010391 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010392 }
10393 }
10394
David Blaikiee4d798f2012-01-20 21:50:17 +000010395 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010396}
10397
Richard Smithf57d8cb2011-12-09 22:58:01 +000010398/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010399static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010400 const Expr *E,
10401 llvm::APSInt *Value,
10402 SourceLocation *Loc) {
10403 if (!E->getType()->isIntegralOrEnumerationType()) {
10404 if (Loc) *Loc = E->getExprLoc();
10405 return false;
10406 }
10407
Richard Smith66e05fe2012-01-18 05:21:49 +000010408 APValue Result;
10409 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010410 return false;
10411
Richard Smith98710fc2014-11-13 23:03:19 +000010412 if (!Result.isInt()) {
10413 if (Loc) *Loc = E->getExprLoc();
10414 return false;
10415 }
10416
Richard Smith66e05fe2012-01-18 05:21:49 +000010417 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010418 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010419}
10420
Craig Toppera31a8822013-08-22 07:09:37 +000010421bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10422 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010423 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010424 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010425
Richard Smith9e575da2012-12-28 13:25:52 +000010426 ICEDiag D = CheckICE(this, Ctx);
10427 if (D.Kind != IK_ICE) {
10428 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010429 return false;
10430 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010431 return true;
10432}
10433
Craig Toppera31a8822013-08-22 07:09:37 +000010434bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010435 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010436 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010437 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10438
10439 if (!isIntegerConstantExpr(Ctx, Loc))
10440 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010441 // The only possible side-effects here are due to UB discovered in the
10442 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10443 // required to treat the expression as an ICE, so we produce the folded
10444 // value.
10445 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010446 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010447 return true;
10448}
Richard Smith66e05fe2012-01-18 05:21:49 +000010449
Craig Toppera31a8822013-08-22 07:09:37 +000010450bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010451 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010452}
10453
Craig Toppera31a8822013-08-22 07:09:37 +000010454bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010455 SourceLocation *Loc) const {
10456 // We support this checking in C++98 mode in order to diagnose compatibility
10457 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010458 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010459
Richard Smith98a0a492012-02-14 21:38:30 +000010460 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010461 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010462 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010463 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010464 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010465
10466 APValue Scratch;
10467 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10468
10469 if (!Diags.empty()) {
10470 IsConstExpr = false;
10471 if (Loc) *Loc = Diags[0].first;
10472 } else if (!IsConstExpr) {
10473 // FIXME: This shouldn't happen.
10474 if (Loc) *Loc = getExprLoc();
10475 }
10476
10477 return IsConstExpr;
10478}
Richard Smith253c2a32012-01-27 01:14:48 +000010479
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010480bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10481 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010482 ArrayRef<const Expr*> Args,
10483 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010484 Expr::EvalStatus Status;
10485 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10486
George Burgess IV177399e2017-01-09 04:12:14 +000010487 LValue ThisVal;
10488 const LValue *ThisPtr = nullptr;
10489 if (This) {
10490#ifndef NDEBUG
10491 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10492 assert(MD && "Don't provide `this` for non-methods.");
10493 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10494#endif
10495 if (EvaluateObjectArgument(Info, This, ThisVal))
10496 ThisPtr = &ThisVal;
10497 if (Info.EvalStatus.HasSideEffects)
10498 return false;
10499 }
10500
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010501 ArgVector ArgValues(Args.size());
10502 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10503 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010504 if ((*I)->isValueDependent() ||
10505 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010506 // If evaluation fails, throw away the argument entirely.
10507 ArgValues[I - Args.begin()] = APValue();
10508 if (Info.EvalStatus.HasSideEffects)
10509 return false;
10510 }
10511
10512 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010513 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010514 ArgValues.data());
10515 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10516}
10517
Richard Smith253c2a32012-01-27 01:14:48 +000010518bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010519 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010520 PartialDiagnosticAt> &Diags) {
10521 // FIXME: It would be useful to check constexpr function templates, but at the
10522 // moment the constant expression evaluator cannot cope with the non-rigorous
10523 // ASTs which we build for dependent expressions.
10524 if (FD->isDependentContext())
10525 return true;
10526
10527 Expr::EvalStatus Status;
10528 Status.Diag = &Diags;
10529
Richard Smith6d4c6582013-11-05 22:18:15 +000010530 EvalInfo Info(FD->getASTContext(), Status,
10531 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010532
10533 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010534 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010535
Richard Smith7525ff62013-05-09 07:14:00 +000010536 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010537 // is a temporary being used as the 'this' pointer.
10538 LValue This;
10539 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010540 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010541
Richard Smith253c2a32012-01-27 01:14:48 +000010542 ArrayRef<const Expr*> Args;
10543
Richard Smith2e312c82012-03-03 22:46:17 +000010544 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010545 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10546 // Evaluate the call as a constant initializer, to allow the construction
10547 // of objects of non-literal types.
10548 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010549 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10550 } else {
10551 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010552 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010553 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010554 }
Richard Smith253c2a32012-01-27 01:14:48 +000010555
10556 return Diags.empty();
10557}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010558
10559bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10560 const FunctionDecl *FD,
10561 SmallVectorImpl<
10562 PartialDiagnosticAt> &Diags) {
10563 Expr::EvalStatus Status;
10564 Status.Diag = &Diags;
10565
10566 EvalInfo Info(FD->getASTContext(), Status,
10567 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10568
10569 // Fabricate a call stack frame to give the arguments a plausible cover story.
10570 ArrayRef<const Expr*> Args;
10571 ArgVector ArgValues(0);
10572 bool Success = EvaluateArgs(Args, ArgValues, Info);
10573 (void)Success;
10574 assert(Success &&
10575 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010576 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010577
10578 APValue ResultScratch;
10579 Evaluate(ResultScratch, Info, E);
10580 return Diags.empty();
10581}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010582
10583bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10584 unsigned Type) const {
10585 if (!getType()->isPointerType())
10586 return false;
10587
10588 Expr::EvalStatus Status;
10589 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010590 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010591}