blob: de0535463808391b8cd682b4970e89a02c3ad5f2 [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 IVe3763372016-12-22 02:50:20 +0000619 /// Evaluate as a constant expression. Continue evaluating if either:
620 /// - We find a MemberExpr with a base that can't be evaluated.
621 /// - We find a variable initialized with a call to a function that has
622 /// the alloc_size attribute on it.
623 /// In either case, the LValue returned shall have an invalid base; in the
624 /// former, the base will be the invalid MemberExpr, in the latter, the
625 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
626 /// said CallExpr.
627 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000628 } EvalMode;
629
630 /// Are we checking whether the expression is a potential constant
631 /// expression?
632 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000633 return EvalMode == EM_PotentialConstantExpression ||
634 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000635 }
636
637 /// Are we checking an expression for overflow?
638 // FIXME: We should check for any kind of undefined or suspicious behavior
639 // in such constructs, not just overflow.
640 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
641
642 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000643 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000644 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000645 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000646 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
647 EvaluatingDecl((const ValueDecl *)nullptr),
648 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000649 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
650 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000651
Richard Smith7525ff62013-05-09 07:14:00 +0000652 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
653 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000654 EvaluatingDeclValue = &Value;
655 }
656
David Blaikiebbafb8a2012-03-11 07:00:24 +0000657 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000658
Richard Smith357362d2011-12-13 06:39:58 +0000659 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000660 // Don't perform any constexpr calls (other than the call we're checking)
661 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000662 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000663 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000664 if (NextCallIndex == 0) {
665 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000666 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000667 return false;
668 }
Richard Smith357362d2011-12-13 06:39:58 +0000669 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
670 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000671 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000672 << getLangOpts().ConstexprCallDepth;
673 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000674 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000675
Richard Smithb228a862012-02-15 02:18:13 +0000676 CallStackFrame *getCallFrame(unsigned CallIndex) {
677 assert(CallIndex && "no call index in getCallFrame");
678 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
679 // be null in this loop.
680 CallStackFrame *Frame = CurrentCall;
681 while (Frame->Index > CallIndex)
682 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000683 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000684 }
685
Richard Smitha3d3bd22013-05-08 02:12:03 +0000686 bool nextStep(const Stmt *S) {
687 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000688 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000689 return false;
690 }
691 --StepsLeft;
692 return true;
693 }
694
Richard Smith357362d2011-12-13 06:39:58 +0000695 private:
696 /// Add a diagnostic to the diagnostics list.
697 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
698 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
699 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
700 return EvalStatus.Diag->back().second;
701 }
702
Richard Smithf6f003a2011-12-16 19:06:07 +0000703 /// Add notes containing a call stack to the current point of evaluation.
704 void addCallStack(unsigned Limit);
705
Faisal Valie690b7a2016-07-02 22:34:24 +0000706 private:
707 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
708 unsigned ExtraNotes, bool IsCCEDiag) {
709
Richard Smith92b1ce02011-12-12 09:28:41 +0000710 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000711 // If we have a prior diagnostic, it will be noting that the expression
712 // isn't a constant expression. This diagnostic is more important,
713 // unless we require this evaluation to produce a constant expression.
714 //
715 // FIXME: We might want to show both diagnostics to the user in
716 // EM_ConstantFold mode.
717 if (!EvalStatus.Diag->empty()) {
718 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000719 case EM_ConstantFold:
720 case EM_IgnoreSideEffects:
721 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000722 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000723 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000724 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000725 case EM_ConstantExpression:
726 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000727 case EM_ConstantExpressionUnevaluated:
728 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000729 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000730 HasActiveDiagnostic = false;
731 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000732 }
733 }
734
Richard Smithf6f003a2011-12-16 19:06:07 +0000735 unsigned CallStackNotes = CallStackDepth - 1;
736 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
737 if (Limit)
738 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000739 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000740 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000741
Richard Smith357362d2011-12-13 06:39:58 +0000742 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000743 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000744 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000745 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
746 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000747 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000748 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000749 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000750 }
Richard Smith357362d2011-12-13 06:39:58 +0000751 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000752 return OptionalDiagnostic();
753 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000754 public:
755 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
756 OptionalDiagnostic
757 FFDiag(SourceLocation Loc,
758 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
759 unsigned ExtraNotes = 0) {
760 return Diag(Loc, DiagId, ExtraNotes, false);
761 }
762
763 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000764 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000765 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000766 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000767 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000768 HasActiveDiagnostic = false;
769 return OptionalDiagnostic();
770 }
771
Richard Smith92b1ce02011-12-12 09:28:41 +0000772 /// Diagnose that the evaluation does not produce a C++11 core constant
773 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000774 ///
775 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
776 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000777 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000778 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000779 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000780 // Don't override a previous diagnostic. Don't bother collecting
781 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000782 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000783 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000784 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000785 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000786 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000787 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000788 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
789 = diag::note_invalid_subexpr_in_const_expr,
790 unsigned ExtraNotes = 0) {
791 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
792 }
Richard Smith357362d2011-12-13 06:39:58 +0000793 /// Add a note to a prior diagnostic.
794 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
795 if (!HasActiveDiagnostic)
796 return OptionalDiagnostic();
797 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000798 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000799
800 /// Add a stack of notes to a prior diagnostic.
801 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
802 if (HasActiveDiagnostic) {
803 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
804 Diags.begin(), Diags.end());
805 }
806 }
Richard Smith253c2a32012-01-27 01:14:48 +0000807
Richard Smith6d4c6582013-11-05 22:18:15 +0000808 /// Should we continue evaluation after encountering a side-effect that we
809 /// couldn't model?
810 bool keepEvaluatingAfterSideEffect() {
811 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000812 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000813 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000814 case EM_EvaluateForOverflow:
815 case EM_IgnoreSideEffects:
816 return true;
817
Richard Smith6d4c6582013-11-05 22:18:15 +0000818 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000819 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000820 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000821 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000822 return false;
823 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000824 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000825 }
826
827 /// Note that we have had a side-effect, and determine whether we should
828 /// keep evaluating.
829 bool noteSideEffect() {
830 EvalStatus.HasSideEffects = true;
831 return keepEvaluatingAfterSideEffect();
832 }
833
Richard Smithce8eca52015-12-08 03:21:47 +0000834 /// Should we continue evaluation after encountering undefined behavior?
835 bool keepEvaluatingAfterUndefinedBehavior() {
836 switch (EvalMode) {
837 case EM_EvaluateForOverflow:
838 case EM_IgnoreSideEffects:
839 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000840 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000841 return true;
842
843 case EM_PotentialConstantExpression:
844 case EM_PotentialConstantExpressionUnevaluated:
845 case EM_ConstantExpression:
846 case EM_ConstantExpressionUnevaluated:
847 return false;
848 }
849 llvm_unreachable("Missed EvalMode case");
850 }
851
852 /// Note that we hit something that was technically undefined behavior, but
853 /// that we can evaluate past it (such as signed overflow or floating-point
854 /// division by zero.)
855 bool noteUndefinedBehavior() {
856 EvalStatus.HasUndefinedBehavior = true;
857 return keepEvaluatingAfterUndefinedBehavior();
858 }
859
Richard Smith253c2a32012-01-27 01:14:48 +0000860 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000861 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000862 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000863 if (!StepsLeft)
864 return false;
865
866 switch (EvalMode) {
867 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000868 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000869 case EM_EvaluateForOverflow:
870 return true;
871
872 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000873 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000874 case EM_ConstantFold:
875 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000876 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000877 return false;
878 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000879 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000880 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000881
George Burgess IV8c892b52016-05-25 22:31:54 +0000882 /// Notes that we failed to evaluate an expression that other expressions
883 /// directly depend on, and determine if we should keep evaluating. This
884 /// should only be called if we actually intend to keep evaluating.
885 ///
886 /// Call noteSideEffect() instead if we may be able to ignore the value that
887 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
888 ///
889 /// (Foo(), 1) // use noteSideEffect
890 /// (Foo() || true) // use noteSideEffect
891 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000892 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000893 // Failure when evaluating some expression often means there is some
894 // subexpression whose evaluation was skipped. Therefore, (because we
895 // don't track whether we skipped an expression when unwinding after an
896 // evaluation failure) every evaluation failure that bubbles up from a
897 // subexpression implies that a side-effect has potentially happened. We
898 // skip setting the HasSideEffects flag to true until we decide to
899 // continue evaluating after that point, which happens here.
900 bool KeepGoing = keepEvaluatingAfterFailure();
901 EvalStatus.HasSideEffects |= KeepGoing;
902 return KeepGoing;
903 }
904
George Burgess IV3a03fab2015-09-04 21:28:13 +0000905 bool allowInvalidBaseExpr() const {
George Burgess IVe3763372016-12-22 02:50:20 +0000906 return EvalMode == EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000907 }
Richard Smith410306b2016-12-12 02:53:20 +0000908
909 class ArrayInitLoopIndex {
910 EvalInfo &Info;
911 uint64_t OuterIndex;
912
913 public:
914 ArrayInitLoopIndex(EvalInfo &Info)
915 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
916 Info.ArrayInitIndex = 0;
917 }
918 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
919
920 operator uint64_t&() { return Info.ArrayInitIndex; }
921 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000922 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000923
924 /// Object used to treat all foldable expressions as constant expressions.
925 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000926 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000927 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000928 bool HadNoPriorDiags;
929 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000930
Richard Smith6d4c6582013-11-05 22:18:15 +0000931 explicit FoldConstant(EvalInfo &Info, bool Enabled)
932 : Info(Info),
933 Enabled(Enabled),
934 HadNoPriorDiags(Info.EvalStatus.Diag &&
935 Info.EvalStatus.Diag->empty() &&
936 !Info.EvalStatus.HasSideEffects),
937 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000938 if (Enabled &&
939 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
940 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000941 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000942 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000943 void keepDiagnostics() { Enabled = false; }
944 ~FoldConstant() {
945 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000946 !Info.EvalStatus.HasSideEffects)
947 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000948 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000949 }
950 };
Richard Smith17100ba2012-02-16 02:46:34 +0000951
George Burgess IV3a03fab2015-09-04 21:28:13 +0000952 /// RAII object used to treat the current evaluation as the correct pointer
953 /// offset fold for the current EvalMode
954 struct FoldOffsetRAII {
955 EvalInfo &Info;
956 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +0000957 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +0000958 : Info(Info), OldMode(Info.EvalMode) {
959 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +0000960 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000961 }
962
963 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
964 };
965
George Burgess IV8c892b52016-05-25 22:31:54 +0000966 /// RAII object used to optionally suppress diagnostics and side-effects from
967 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000968 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000969 /// Pair of EvalInfo, and a bit that stores whether or not we were
970 /// speculatively evaluating when we created this RAII.
971 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000972 Expr::EvalStatus Old;
973
George Burgess IV8c892b52016-05-25 22:31:54 +0000974 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
975 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
976 Old = Other.Old;
977 Other.InfoAndOldSpecEval.setPointer(nullptr);
978 }
979
980 void maybeRestoreState() {
981 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
982 if (!Info)
983 return;
984
985 Info->EvalStatus = Old;
986 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
987 }
988
Richard Smith17100ba2012-02-16 02:46:34 +0000989 public:
George Burgess IV8c892b52016-05-25 22:31:54 +0000990 SpeculativeEvaluationRAII() = default;
991
992 SpeculativeEvaluationRAII(
993 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
994 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
995 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +0000996 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +0000997 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000998 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000999
1000 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1001 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1002 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001003 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001004
1005 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1006 maybeRestoreState();
1007 moveFromAndCancel(std::move(Other));
1008 return *this;
1009 }
1010
1011 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001012 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001013
1014 /// RAII object wrapping a full-expression or block scope, and handling
1015 /// the ending of the lifetime of temporaries created within it.
1016 template<bool IsFullExpression>
1017 class ScopeRAII {
1018 EvalInfo &Info;
1019 unsigned OldStackSize;
1020 public:
1021 ScopeRAII(EvalInfo &Info)
1022 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1023 ~ScopeRAII() {
1024 // Body moved to a static method to encourage the compiler to inline away
1025 // instances of this class.
1026 cleanup(Info, OldStackSize);
1027 }
1028 private:
1029 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1030 unsigned NewEnd = OldStackSize;
1031 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1032 I != N; ++I) {
1033 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1034 // Full-expression cleanup of a lifetime-extended temporary: nothing
1035 // to do, just move this cleanup to the right place in the stack.
1036 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1037 ++NewEnd;
1038 } else {
1039 // End the lifetime of the object.
1040 Info.CleanupStack[I].endLifetime();
1041 }
1042 }
1043 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1044 Info.CleanupStack.end());
1045 }
1046 };
1047 typedef ScopeRAII<false> BlockScopeRAII;
1048 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001049}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001050
Richard Smitha8105bc2012-01-06 16:39:00 +00001051bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1052 CheckSubobjectKind CSK) {
1053 if (Invalid)
1054 return false;
1055 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001056 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001057 << CSK;
1058 setInvalid();
1059 return false;
1060 }
1061 return true;
1062}
1063
1064void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Richard Smithd6cc1982017-01-31 02:23:02 +00001065 const Expr *E, APSInt N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001066 // If we're complaining, we must be able to statically determine the size of
1067 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001068 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001069 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001070 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001071 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001072 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001073 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001074 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001075 setInvalid();
1076}
1077
Richard Smithf6f003a2011-12-16 19:06:07 +00001078CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1079 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001080 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001081 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1082 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001083 Info.CurrentCall = this;
1084 ++Info.CallStackDepth;
1085}
1086
1087CallStackFrame::~CallStackFrame() {
1088 assert(Info.CurrentCall == this && "calls retired out of order");
1089 --Info.CallStackDepth;
1090 Info.CurrentCall = Caller;
1091}
1092
Richard Smith08d6a2c2013-07-24 07:11:57 +00001093APValue &CallStackFrame::createTemporary(const void *Key,
1094 bool IsLifetimeExtended) {
1095 APValue &Result = Temporaries[Key];
1096 assert(Result.isUninit() && "temporary created multiple times");
1097 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1098 return Result;
1099}
1100
Richard Smith84401042013-06-03 05:03:02 +00001101static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001102
1103void EvalInfo::addCallStack(unsigned Limit) {
1104 // Determine which calls to skip, if any.
1105 unsigned ActiveCalls = CallStackDepth - 1;
1106 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1107 if (Limit && Limit < ActiveCalls) {
1108 SkipStart = Limit / 2 + Limit % 2;
1109 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001110 }
1111
Richard Smithf6f003a2011-12-16 19:06:07 +00001112 // Walk the call stack and add the diagnostics.
1113 unsigned CallIdx = 0;
1114 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1115 Frame = Frame->Caller, ++CallIdx) {
1116 // Skip this call?
1117 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1118 if (CallIdx == SkipStart) {
1119 // Note that we're skipping calls.
1120 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1121 << unsigned(ActiveCalls - Limit);
1122 }
1123 continue;
1124 }
1125
Richard Smith5179eb72016-06-28 19:03:57 +00001126 // Use a different note for an inheriting constructor, because from the
1127 // user's perspective it's not really a function at all.
1128 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1129 if (CD->isInheritingConstructor()) {
1130 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1131 << CD->getParent();
1132 continue;
1133 }
1134 }
1135
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001136 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001137 llvm::raw_svector_ostream Out(Buffer);
1138 describeCall(Frame, Out);
1139 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1140 }
1141}
1142
1143namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001144 struct ComplexValue {
1145 private:
1146 bool IsInt;
1147
1148 public:
1149 APSInt IntReal, IntImag;
1150 APFloat FloatReal, FloatImag;
1151
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001152 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001153
1154 void makeComplexFloat() { IsInt = false; }
1155 bool isComplexFloat() const { return !IsInt; }
1156 APFloat &getComplexFloatReal() { return FloatReal; }
1157 APFloat &getComplexFloatImag() { return FloatImag; }
1158
1159 void makeComplexInt() { IsInt = true; }
1160 bool isComplexInt() const { return IsInt; }
1161 APSInt &getComplexIntReal() { return IntReal; }
1162 APSInt &getComplexIntImag() { return IntImag; }
1163
Richard Smith2e312c82012-03-03 22:46:17 +00001164 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001165 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001166 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001167 else
Richard Smith2e312c82012-03-03 22:46:17 +00001168 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001169 }
Richard Smith2e312c82012-03-03 22:46:17 +00001170 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001171 assert(v.isComplexFloat() || v.isComplexInt());
1172 if (v.isComplexFloat()) {
1173 makeComplexFloat();
1174 FloatReal = v.getComplexFloatReal();
1175 FloatImag = v.getComplexFloatImag();
1176 } else {
1177 makeComplexInt();
1178 IntReal = v.getComplexIntReal();
1179 IntImag = v.getComplexIntImag();
1180 }
1181 }
John McCall93d91dc2010-05-07 17:22:02 +00001182 };
John McCall45d55e42010-05-07 21:00:08 +00001183
1184 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001185 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001186 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001187 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001188 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001189 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001190 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001191
Richard Smithce40ad62011-11-12 22:28:03 +00001192 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001193 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001194 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001195 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001196 SubobjectDesignator &getLValueDesignator() { return Designator; }
1197 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001198 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001199
Richard Smith2e312c82012-03-03 22:46:17 +00001200 void moveInto(APValue &V) const {
1201 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001202 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1203 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001204 else {
1205 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1206 assert(!Designator.FirstEntryIsAnUnsizedArray &&
1207 "Unsized array with a valid base?");
Richard Smith2e312c82012-03-03 22:46:17 +00001208 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001209 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001210 }
John McCall45d55e42010-05-07 21:00:08 +00001211 }
Richard Smith2e312c82012-03-03 22:46:17 +00001212 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001213 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001214 Base = V.getLValueBase();
1215 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001216 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001217 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001218 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001219 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001220 }
1221
Yaxun Liu402804b2016-12-15 08:09:08 +00001222 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
1223 bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
George Burgess IVe3763372016-12-22 02:50:20 +00001224#ifndef NDEBUG
1225 // We only allow a few types of invalid bases. Enforce that here.
1226 if (BInvalid) {
1227 const auto *E = B.get<const Expr *>();
1228 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1229 "Unexpected type of invalid base");
1230 }
1231#endif
1232
Richard Smithce40ad62011-11-12 22:28:03 +00001233 Base = B;
Yaxun Liu402804b2016-12-15 08:09:08 +00001234 Offset = CharUnits::fromQuantity(Offset_);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001235 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001236 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001237 Designator = SubobjectDesignator(getType(B));
Yaxun Liu402804b2016-12-15 08:09:08 +00001238 IsNullPtr = IsNullPtr_;
Richard Smitha8105bc2012-01-06 16:39:00 +00001239 }
1240
George Burgess IV3a03fab2015-09-04 21:28:13 +00001241 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1242 set(B, I, true);
1243 }
1244
Richard Smitha8105bc2012-01-06 16:39:00 +00001245 // Check that this LValue is not based on a null pointer. If it is, produce
1246 // a diagnostic and mark the designator as invalid.
1247 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1248 CheckSubobjectKind CSK) {
1249 if (Designator.Invalid)
1250 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001251 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001252 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001253 << CSK;
1254 Designator.setInvalid();
1255 return false;
1256 }
1257 return true;
1258 }
1259
1260 // Check this LValue refers to an object. If not, set the designator to be
1261 // invalid and emit a diagnostic.
1262 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001263 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001264 Designator.checkSubobject(Info, E, CSK);
1265 }
1266
1267 void addDecl(EvalInfo &Info, const Expr *E,
1268 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001269 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1270 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001271 }
George Burgess IVe3763372016-12-22 02:50:20 +00001272 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1273 assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1274 assert(isBaseAnAllocSizeCall(Base) &&
1275 "Only alloc_size bases can have unsized arrays");
1276 Designator.FirstEntryIsAnUnsizedArray = true;
1277 Designator.addUnsizedArrayUnchecked(ElemTy);
1278 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001279 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001280 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1281 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001282 }
Richard Smith66c96992012-02-18 22:04:06 +00001283 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001284 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1285 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001286 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001287 void clearIsNullPointer() {
1288 IsNullPtr = false;
1289 }
Richard Smithd6cc1982017-01-31 02:23:02 +00001290 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, APSInt Index,
Yaxun Liu402804b2016-12-15 08:09:08 +00001291 CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001292 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1293 // but we're not required to diagnose it and it's valid in C++.)
1294 if (!Index)
1295 return;
1296
1297 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1298 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1299 // offsets.
1300 uint64_t Offset64 = Offset.getQuantity();
1301 uint64_t ElemSize64 = ElementSize.getQuantity();
1302 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1303 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1304
1305 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001306 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001307 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001308 }
1309 void adjustOffset(CharUnits N) {
1310 Offset += N;
1311 if (N.getQuantity())
1312 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001313 }
John McCall45d55e42010-05-07 21:00:08 +00001314 };
Richard Smith027bf112011-11-17 22:56:20 +00001315
1316 struct MemberPtr {
1317 MemberPtr() {}
1318 explicit MemberPtr(const ValueDecl *Decl) :
1319 DeclAndIsDerivedMember(Decl, false), Path() {}
1320
1321 /// The member or (direct or indirect) field referred to by this member
1322 /// pointer, or 0 if this is a null member pointer.
1323 const ValueDecl *getDecl() const {
1324 return DeclAndIsDerivedMember.getPointer();
1325 }
1326 /// Is this actually a member of some type derived from the relevant class?
1327 bool isDerivedMember() const {
1328 return DeclAndIsDerivedMember.getInt();
1329 }
1330 /// Get the class which the declaration actually lives in.
1331 const CXXRecordDecl *getContainingRecord() const {
1332 return cast<CXXRecordDecl>(
1333 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1334 }
1335
Richard Smith2e312c82012-03-03 22:46:17 +00001336 void moveInto(APValue &V) const {
1337 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001338 }
Richard Smith2e312c82012-03-03 22:46:17 +00001339 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001340 assert(V.isMemberPointer());
1341 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1342 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1343 Path.clear();
1344 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1345 Path.insert(Path.end(), P.begin(), P.end());
1346 }
1347
1348 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1349 /// whether the member is a member of some class derived from the class type
1350 /// of the member pointer.
1351 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1352 /// Path - The path of base/derived classes from the member declaration's
1353 /// class (exclusive) to the class type of the member pointer (inclusive).
1354 SmallVector<const CXXRecordDecl*, 4> Path;
1355
1356 /// Perform a cast towards the class of the Decl (either up or down the
1357 /// hierarchy).
1358 bool castBack(const CXXRecordDecl *Class) {
1359 assert(!Path.empty());
1360 const CXXRecordDecl *Expected;
1361 if (Path.size() >= 2)
1362 Expected = Path[Path.size() - 2];
1363 else
1364 Expected = getContainingRecord();
1365 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1366 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1367 // if B does not contain the original member and is not a base or
1368 // derived class of the class containing the original member, the result
1369 // of the cast is undefined.
1370 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1371 // (D::*). We consider that to be a language defect.
1372 return false;
1373 }
1374 Path.pop_back();
1375 return true;
1376 }
1377 /// Perform a base-to-derived member pointer cast.
1378 bool castToDerived(const CXXRecordDecl *Derived) {
1379 if (!getDecl())
1380 return true;
1381 if (!isDerivedMember()) {
1382 Path.push_back(Derived);
1383 return true;
1384 }
1385 if (!castBack(Derived))
1386 return false;
1387 if (Path.empty())
1388 DeclAndIsDerivedMember.setInt(false);
1389 return true;
1390 }
1391 /// Perform a derived-to-base member pointer cast.
1392 bool castToBase(const CXXRecordDecl *Base) {
1393 if (!getDecl())
1394 return true;
1395 if (Path.empty())
1396 DeclAndIsDerivedMember.setInt(true);
1397 if (isDerivedMember()) {
1398 Path.push_back(Base);
1399 return true;
1400 }
1401 return castBack(Base);
1402 }
1403 };
Richard Smith357362d2011-12-13 06:39:58 +00001404
Richard Smith7bb00672012-02-01 01:42:44 +00001405 /// Compare two member pointers, which are assumed to be of the same type.
1406 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1407 if (!LHS.getDecl() || !RHS.getDecl())
1408 return !LHS.getDecl() && !RHS.getDecl();
1409 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1410 return false;
1411 return LHS.Path == RHS.Path;
1412 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001413}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001414
Richard Smith2e312c82012-03-03 22:46:17 +00001415static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001416static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1417 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001418 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001419static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1420static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
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) {
Alexey Bataevec474782014-10-09 08:45:04 +00002397 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2398 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2399 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002400 const StringLiteral *S = cast<StringLiteral>(Lit);
2401 const ConstantArrayType *CAT =
2402 Info.Ctx.getAsConstantArrayType(S->getType());
2403 assert(CAT && "string literal isn't an array");
2404 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002405 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002406
2407 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002408 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002409 if (Index < S->getLength())
2410 Value = S->getCodeUnit(Index);
2411 return Value;
2412}
2413
Richard Smith3da88fa2013-04-26 14:36:30 +00002414// Expand a string literal into an array of characters.
2415static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2416 APValue &Result) {
2417 const StringLiteral *S = cast<StringLiteral>(Lit);
2418 const ConstantArrayType *CAT =
2419 Info.Ctx.getAsConstantArrayType(S->getType());
2420 assert(CAT && "string literal isn't an array");
2421 QualType CharType = CAT->getElementType();
2422 assert(CharType->isIntegerType() && "unexpected character type");
2423
2424 unsigned Elts = CAT->getSize().getZExtValue();
2425 Result = APValue(APValue::UninitArray(),
2426 std::min(S->getLength(), Elts), Elts);
2427 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2428 CharType->isUnsignedIntegerType());
2429 if (Result.hasArrayFiller())
2430 Result.getArrayFiller() = APValue(Value);
2431 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2432 Value = S->getCodeUnit(I);
2433 Result.getArrayInitializedElt(I) = APValue(Value);
2434 }
2435}
2436
2437// Expand an array so that it has more than Index filled elements.
2438static void expandArray(APValue &Array, unsigned Index) {
2439 unsigned Size = Array.getArraySize();
2440 assert(Index < Size);
2441
2442 // Always at least double the number of elements for which we store a value.
2443 unsigned OldElts = Array.getArrayInitializedElts();
2444 unsigned NewElts = std::max(Index+1, OldElts * 2);
2445 NewElts = std::min(Size, std::max(NewElts, 8u));
2446
2447 // Copy the data across.
2448 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2449 for (unsigned I = 0; I != OldElts; ++I)
2450 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2451 for (unsigned I = OldElts; I != NewElts; ++I)
2452 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2453 if (NewValue.hasArrayFiller())
2454 NewValue.getArrayFiller() = Array.getArrayFiller();
2455 Array.swap(NewValue);
2456}
2457
Richard Smithb01fe402014-09-16 01:24:02 +00002458/// Determine whether a type would actually be read by an lvalue-to-rvalue
2459/// conversion. If it's of class type, we may assume that the copy operation
2460/// is trivial. Note that this is never true for a union type with fields
2461/// (because the copy always "reads" the active member) and always true for
2462/// a non-class type.
2463static bool isReadByLvalueToRvalueConversion(QualType T) {
2464 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2465 if (!RD || (RD->isUnion() && !RD->field_empty()))
2466 return true;
2467 if (RD->isEmpty())
2468 return false;
2469
2470 for (auto *Field : RD->fields())
2471 if (isReadByLvalueToRvalueConversion(Field->getType()))
2472 return true;
2473
2474 for (auto &BaseSpec : RD->bases())
2475 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2476 return true;
2477
2478 return false;
2479}
2480
2481/// Diagnose an attempt to read from any unreadable field within the specified
2482/// type, which might be a class type.
2483static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2484 QualType T) {
2485 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2486 if (!RD)
2487 return false;
2488
2489 if (!RD->hasMutableFields())
2490 return false;
2491
2492 for (auto *Field : RD->fields()) {
2493 // If we're actually going to read this field in some way, then it can't
2494 // be mutable. If we're in a union, then assigning to a mutable field
2495 // (even an empty one) can change the active member, so that's not OK.
2496 // FIXME: Add core issue number for the union case.
2497 if (Field->isMutable() &&
2498 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002499 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002500 Info.Note(Field->getLocation(), diag::note_declared_at);
2501 return true;
2502 }
2503
2504 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2505 return true;
2506 }
2507
2508 for (auto &BaseSpec : RD->bases())
2509 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2510 return true;
2511
2512 // All mutable fields were empty, and thus not actually read.
2513 return false;
2514}
2515
Richard Smith861b5b52013-05-07 23:34:45 +00002516/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002517enum AccessKinds {
2518 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002519 AK_Assign,
2520 AK_Increment,
2521 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002522};
2523
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002524namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002525/// A handle to a complete object (an object that is not a subobject of
2526/// another object).
2527struct CompleteObject {
2528 /// The value of the complete object.
2529 APValue *Value;
2530 /// The type of the complete object.
2531 QualType Type;
2532
Craig Topper36250ad2014-05-12 05:36:57 +00002533 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002534 CompleteObject(APValue *Value, QualType Type)
2535 : Value(Value), Type(Type) {
2536 assert(Value && "missing value for complete object");
2537 }
2538
Aaron Ballman67347662015-02-15 22:00:28 +00002539 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002540};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002541} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002542
Richard Smith3da88fa2013-04-26 14:36:30 +00002543/// Find the designated sub-object of an rvalue.
2544template<typename SubobjectHandler>
2545typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002546findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002547 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002548 if (Sub.Invalid)
2549 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002550 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002551 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002552 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002553 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002554 << handler.AccessKind;
2555 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002556 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002557 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002558 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002559
Richard Smith3229b742013-05-05 21:17:10 +00002560 APValue *O = Obj.Value;
2561 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002562 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002563
Richard Smithd62306a2011-11-10 06:34:14 +00002564 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002565 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2566 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002567 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002568 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002569 return handler.failed();
2570 }
2571
Richard Smith49ca8aa2013-08-06 07:09:20 +00002572 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002573 // If we are reading an object of class type, there may still be more
2574 // things we need to check: if there are any mutable subobjects, we
2575 // cannot perform this read. (This only happens when performing a trivial
2576 // copy or assignment.)
2577 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2578 diagnoseUnreadableFields(Info, E, ObjType))
2579 return handler.failed();
2580
Richard Smith49ca8aa2013-08-06 07:09:20 +00002581 if (!handler.found(*O, ObjType))
2582 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002583
Richard Smith49ca8aa2013-08-06 07:09:20 +00002584 // If we modified a bit-field, truncate it to the right width.
2585 if (handler.AccessKind != AK_Read &&
2586 LastField && LastField->isBitField() &&
2587 !truncateBitfieldValue(Info, E, *O, LastField))
2588 return false;
2589
2590 return true;
2591 }
2592
Craig Topper36250ad2014-05-12 05:36:57 +00002593 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002594 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002595 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002596 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002597 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002598 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002599 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002600 // Note, it should not be possible to form a pointer with a valid
2601 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002602 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002603 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002604 << handler.AccessKind;
2605 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002606 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002607 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002608 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002609
2610 ObjType = CAT->getElementType();
2611
Richard Smith14a94132012-02-17 03:35:37 +00002612 // An array object is represented as either an Array APValue or as an
2613 // LValue which refers to a string literal.
2614 if (O->isLValue()) {
2615 assert(I == N - 1 && "extracting subobject of character?");
2616 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002617 if (handler.AccessKind != AK_Read)
2618 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2619 *O);
2620 else
2621 return handler.foundString(*O, ObjType, Index);
2622 }
2623
2624 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002625 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002626 else if (handler.AccessKind != AK_Read) {
2627 expandArray(*O, Index);
2628 O = &O->getArrayInitializedElt(Index);
2629 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002630 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002631 } else if (ObjType->isAnyComplexType()) {
2632 // Next subobject is a complex number.
2633 uint64_t Index = Sub.Entries[I].ArrayIndex;
2634 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002635 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002636 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002637 << handler.AccessKind;
2638 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002639 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002640 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002641 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002642
2643 bool WasConstQualified = ObjType.isConstQualified();
2644 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2645 if (WasConstQualified)
2646 ObjType.addConst();
2647
Richard Smith66c96992012-02-18 22:04:06 +00002648 assert(I == N - 1 && "extracting subobject of scalar?");
2649 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002650 return handler.found(Index ? O->getComplexIntImag()
2651 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002652 } else {
2653 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002654 return handler.found(Index ? O->getComplexFloatImag()
2655 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002656 }
Richard Smithd62306a2011-11-10 06:34:14 +00002657 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002658 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002659 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002660 << Field;
2661 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002662 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002663 }
2664
Richard Smithd62306a2011-11-10 06:34:14 +00002665 // Next subobject is a class, struct or union field.
2666 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2667 if (RD->isUnion()) {
2668 const FieldDecl *UnionField = O->getUnionField();
2669 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002670 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002671 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002672 << handler.AccessKind << Field << !UnionField << UnionField;
2673 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002674 }
Richard Smithd62306a2011-11-10 06:34:14 +00002675 O = &O->getUnionValue();
2676 } else
2677 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002678
2679 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002680 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002681 if (WasConstQualified && !Field->isMutable())
2682 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002683
2684 if (ObjType.isVolatileQualified()) {
2685 if (Info.getLangOpts().CPlusPlus) {
2686 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002687 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002688 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002689 Info.Note(Field->getLocation(), diag::note_declared_at);
2690 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002691 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002692 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002693 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002694 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002695
2696 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002697 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002698 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002699 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2700 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2701 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002702
2703 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002704 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002705 if (WasConstQualified)
2706 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002707 }
2708 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002709}
2710
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002711namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002712struct ExtractSubobjectHandler {
2713 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002714 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002715
2716 static const AccessKinds AccessKind = AK_Read;
2717
2718 typedef bool result_type;
2719 bool failed() { return false; }
2720 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002721 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002722 return true;
2723 }
2724 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002725 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002726 return true;
2727 }
2728 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002729 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002730 return true;
2731 }
2732 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002733 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002734 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2735 return true;
2736 }
2737};
Richard Smith3229b742013-05-05 21:17:10 +00002738} // end anonymous namespace
2739
Richard Smith3da88fa2013-04-26 14:36:30 +00002740const AccessKinds ExtractSubobjectHandler::AccessKind;
2741
2742/// Extract the designated sub-object of an rvalue.
2743static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002744 const CompleteObject &Obj,
2745 const SubobjectDesignator &Sub,
2746 APValue &Result) {
2747 ExtractSubobjectHandler Handler = { Info, Result };
2748 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002749}
2750
Richard Smith3229b742013-05-05 21:17:10 +00002751namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002752struct ModifySubobjectHandler {
2753 EvalInfo &Info;
2754 APValue &NewVal;
2755 const Expr *E;
2756
2757 typedef bool result_type;
2758 static const AccessKinds AccessKind = AK_Assign;
2759
2760 bool checkConst(QualType QT) {
2761 // Assigning to a const object has undefined behavior.
2762 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002763 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002764 return false;
2765 }
2766 return true;
2767 }
2768
2769 bool failed() { return false; }
2770 bool found(APValue &Subobj, QualType SubobjType) {
2771 if (!checkConst(SubobjType))
2772 return false;
2773 // We've been given ownership of NewVal, so just swap it in.
2774 Subobj.swap(NewVal);
2775 return true;
2776 }
2777 bool found(APSInt &Value, QualType SubobjType) {
2778 if (!checkConst(SubobjType))
2779 return false;
2780 if (!NewVal.isInt()) {
2781 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002782 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002783 return false;
2784 }
2785 Value = NewVal.getInt();
2786 return true;
2787 }
2788 bool found(APFloat &Value, QualType SubobjType) {
2789 if (!checkConst(SubobjType))
2790 return false;
2791 Value = NewVal.getFloat();
2792 return true;
2793 }
2794 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2795 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2796 }
2797};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002798} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002799
Richard Smith3229b742013-05-05 21:17:10 +00002800const AccessKinds ModifySubobjectHandler::AccessKind;
2801
Richard Smith3da88fa2013-04-26 14:36:30 +00002802/// Update the designated sub-object of an rvalue to the given value.
2803static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002804 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002805 const SubobjectDesignator &Sub,
2806 APValue &NewVal) {
2807 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002808 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002809}
2810
Richard Smith84f6dcf2012-02-02 01:16:57 +00002811/// Find the position where two subobject designators diverge, or equivalently
2812/// the length of the common initial subsequence.
2813static unsigned FindDesignatorMismatch(QualType ObjType,
2814 const SubobjectDesignator &A,
2815 const SubobjectDesignator &B,
2816 bool &WasArrayIndex) {
2817 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2818 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002819 if (!ObjType.isNull() &&
2820 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002821 // Next subobject is an array element.
2822 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2823 WasArrayIndex = true;
2824 return I;
2825 }
Richard Smith66c96992012-02-18 22:04:06 +00002826 if (ObjType->isAnyComplexType())
2827 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2828 else
2829 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002830 } else {
2831 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2832 WasArrayIndex = false;
2833 return I;
2834 }
2835 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2836 // Next subobject is a field.
2837 ObjType = FD->getType();
2838 else
2839 // Next subobject is a base class.
2840 ObjType = QualType();
2841 }
2842 }
2843 WasArrayIndex = false;
2844 return I;
2845}
2846
2847/// Determine whether the given subobject designators refer to elements of the
2848/// same array object.
2849static bool AreElementsOfSameArray(QualType ObjType,
2850 const SubobjectDesignator &A,
2851 const SubobjectDesignator &B) {
2852 if (A.Entries.size() != B.Entries.size())
2853 return false;
2854
George Burgess IVa51c4072015-10-16 01:49:01 +00002855 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002856 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2857 // A is a subobject of the array element.
2858 return false;
2859
2860 // If A (and B) designates an array element, the last entry will be the array
2861 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2862 // of length 1' case, and the entire path must match.
2863 bool WasArrayIndex;
2864 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2865 return CommonLength >= A.Entries.size() - IsArray;
2866}
2867
Richard Smith3229b742013-05-05 21:17:10 +00002868/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002869static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2870 AccessKinds AK, const LValue &LVal,
2871 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002872 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002873 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002874 return CompleteObject();
2875 }
2876
Craig Topper36250ad2014-05-12 05:36:57 +00002877 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002878 if (LVal.CallIndex) {
2879 Frame = Info.getCallFrame(LVal.CallIndex);
2880 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002881 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002882 << AK << LVal.Base.is<const ValueDecl*>();
2883 NoteLValueLocation(Info, LVal.Base);
2884 return CompleteObject();
2885 }
Richard Smith3229b742013-05-05 21:17:10 +00002886 }
2887
2888 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2889 // is not a constant expression (even if the object is non-volatile). We also
2890 // apply this rule to C++98, in order to conform to the expected 'volatile'
2891 // semantics.
2892 if (LValType.isVolatileQualified()) {
2893 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002894 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002895 << AK << LValType;
2896 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002897 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002898 return CompleteObject();
2899 }
2900
2901 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002902 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002903 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002904
2905 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2906 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2907 // In C++11, constexpr, non-volatile variables initialized with constant
2908 // expressions are constant expressions too. Inside constexpr functions,
2909 // parameters are constant expressions even if they're non-const.
2910 // In C++1y, objects local to a constant expression (those with a Frame) are
2911 // both readable and writable inside constant expressions.
2912 // In C, such things can also be folded, although they are not ICEs.
2913 const VarDecl *VD = dyn_cast<VarDecl>(D);
2914 if (VD) {
2915 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2916 VD = VDef;
2917 }
2918 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002919 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002920 return CompleteObject();
2921 }
2922
2923 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002924 if (BaseType.isVolatileQualified()) {
2925 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002926 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002927 << AK << 1 << VD;
2928 Info.Note(VD->getLocation(), diag::note_declared_at);
2929 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002930 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002931 }
2932 return CompleteObject();
2933 }
2934
2935 // Unless we're looking at a local variable or argument in a constexpr call,
2936 // the variable we're reading must be const.
2937 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002938 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002939 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2940 // OK, we can read and modify an object if we're in the process of
2941 // evaluating its initializer, because its lifetime began in this
2942 // evaluation.
2943 } else if (AK != AK_Read) {
2944 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002945 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002946 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00002947 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002948 // OK, we can read this variable.
2949 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002950 // In OpenCL if a variable is in constant address space it is a const value.
2951 if (!(BaseType.isConstQualified() ||
2952 (Info.getLangOpts().OpenCL &&
2953 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002954 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002955 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002956 Info.Note(VD->getLocation(), diag::note_declared_at);
2957 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002958 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002959 }
2960 return CompleteObject();
2961 }
2962 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2963 // We support folding of const floating-point types, in order to make
2964 // static const data members of such types (supported as an extension)
2965 // more useful.
2966 if (Info.getLangOpts().CPlusPlus11) {
2967 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2968 Info.Note(VD->getLocation(), diag::note_declared_at);
2969 } else {
2970 Info.CCEDiag(E);
2971 }
George Burgess IVb5316982016-12-27 05:33:20 +00002972 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
2973 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
2974 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00002975 } else {
2976 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00002977 if (Info.checkingPotentialConstantExpression() &&
2978 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2979 // The definition of this variable could be constexpr. We can't
2980 // access it right now, but may be able to in future.
2981 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002982 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002983 Info.Note(VD->getLocation(), diag::note_declared_at);
2984 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002985 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002986 }
2987 return CompleteObject();
2988 }
2989 }
2990
2991 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2992 return CompleteObject();
2993 } else {
2994 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2995
2996 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002997 if (const MaterializeTemporaryExpr *MTE =
2998 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2999 assert(MTE->getStorageDuration() == SD_Static &&
3000 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003001
Richard Smithe6c01442013-06-05 00:46:14 +00003002 // Per C++1y [expr.const]p2:
3003 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3004 // - a [...] glvalue of integral or enumeration type that refers to
3005 // a non-volatile const object [...]
3006 // [...]
3007 // - a [...] glvalue of literal type that refers to a non-volatile
3008 // object whose lifetime began within the evaluation of e.
3009 //
3010 // C++11 misses the 'began within the evaluation of e' check and
3011 // instead allows all temporaries, including things like:
3012 // int &&r = 1;
3013 // int x = ++r;
3014 // constexpr int k = r;
3015 // Therefore we use the C++1y rules in C++11 too.
3016 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3017 const ValueDecl *ED = MTE->getExtendingDecl();
3018 if (!(BaseType.isConstQualified() &&
3019 BaseType->isIntegralOrEnumerationType()) &&
3020 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003021 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003022 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3023 return CompleteObject();
3024 }
3025
3026 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3027 assert(BaseVal && "got reference to unevaluated temporary");
3028 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003029 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003030 return CompleteObject();
3031 }
3032 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003033 BaseVal = Frame->getTemporary(Base);
3034 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003035 }
Richard Smith3229b742013-05-05 21:17:10 +00003036
3037 // Volatile temporary objects cannot be accessed in constant expressions.
3038 if (BaseType.isVolatileQualified()) {
3039 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003040 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003041 << AK << 0;
3042 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3043 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003044 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003045 }
3046 return CompleteObject();
3047 }
3048 }
3049
Richard Smith7525ff62013-05-09 07:14:00 +00003050 // During the construction of an object, it is not yet 'const'.
3051 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3052 // and this doesn't do quite the right thing for const subobjects of the
3053 // object under construction.
3054 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3055 BaseType = Info.Ctx.getCanonicalType(BaseType);
3056 BaseType.removeLocalConst();
3057 }
3058
Richard Smith6d4c6582013-11-05 22:18:15 +00003059 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003060 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003061 //
3062 // FIXME: Not all local state is mutable. Allow local constant subobjects
3063 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003064 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3065 Info.EvalStatus.HasSideEffects) ||
3066 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003067 return CompleteObject();
3068
3069 return CompleteObject(BaseVal, BaseType);
3070}
3071
Richard Smith243ef902013-05-05 23:31:59 +00003072/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3073/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3074/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003075///
3076/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003077/// \param Conv - The expression for which we are performing the conversion.
3078/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003079/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3080/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003081/// \param LVal - The glvalue on which we are attempting to perform this action.
3082/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003083static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003084 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003085 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003086 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003087 return false;
3088
Richard Smith3229b742013-05-05 21:17:10 +00003089 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003090 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003091 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003092 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3093 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3094 // initializer until now for such expressions. Such an expression can't be
3095 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003096 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003097 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003098 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003099 }
Richard Smith3229b742013-05-05 21:17:10 +00003100 APValue Lit;
3101 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3102 return false;
3103 CompleteObject LitObj(&Lit, Base->getType());
3104 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003105 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003106 // We represent a string literal array as an lvalue pointing at the
3107 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003108 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003109 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3110 CompleteObject StrObj(&Str, Base->getType());
3111 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003112 }
Richard Smith11562c52011-10-28 17:51:58 +00003113 }
3114
Richard Smith3229b742013-05-05 21:17:10 +00003115 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3116 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003117}
3118
3119/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003120static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003121 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003122 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003123 return false;
3124
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003125 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003126 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003127 return false;
3128 }
3129
Richard Smith3229b742013-05-05 21:17:10 +00003130 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3131 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00003132}
3133
Richard Smith243ef902013-05-05 23:31:59 +00003134static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3135 return T->isSignedIntegerType() &&
3136 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3137}
3138
3139namespace {
Richard Smith43e77732013-05-07 04:50:00 +00003140struct CompoundAssignSubobjectHandler {
3141 EvalInfo &Info;
3142 const Expr *E;
3143 QualType PromotedLHSType;
3144 BinaryOperatorKind Opcode;
3145 const APValue &RHS;
3146
3147 static const AccessKinds AccessKind = AK_Assign;
3148
3149 typedef bool result_type;
3150
3151 bool checkConst(QualType QT) {
3152 // Assigning to a const object has undefined behavior.
3153 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003154 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003155 return false;
3156 }
3157 return true;
3158 }
3159
3160 bool failed() { return false; }
3161 bool found(APValue &Subobj, QualType SubobjType) {
3162 switch (Subobj.getKind()) {
3163 case APValue::Int:
3164 return found(Subobj.getInt(), SubobjType);
3165 case APValue::Float:
3166 return found(Subobj.getFloat(), SubobjType);
3167 case APValue::ComplexInt:
3168 case APValue::ComplexFloat:
3169 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003170 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003171 return false;
3172 case APValue::LValue:
3173 return foundPointer(Subobj, SubobjType);
3174 default:
3175 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003176 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003177 return false;
3178 }
3179 }
3180 bool found(APSInt &Value, QualType SubobjType) {
3181 if (!checkConst(SubobjType))
3182 return false;
3183
3184 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3185 // We don't support compound assignment on integer-cast-to-pointer
3186 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003187 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003188 return false;
3189 }
3190
3191 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3192 SubobjType, Value);
3193 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3194 return false;
3195 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3196 return true;
3197 }
3198 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003199 return checkConst(SubobjType) &&
3200 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3201 Value) &&
3202 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3203 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003204 }
3205 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3206 if (!checkConst(SubobjType))
3207 return false;
3208
3209 QualType PointeeType;
3210 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3211 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003212
3213 if (PointeeType.isNull() || !RHS.isInt() ||
3214 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003215 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003216 return false;
3217 }
3218
Richard Smithd6cc1982017-01-31 02:23:02 +00003219 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003220 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003221 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003222
3223 LValue LVal;
3224 LVal.setFrom(Info.Ctx, Subobj);
3225 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3226 return false;
3227 LVal.moveInto(Subobj);
3228 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003229 }
3230 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3231 llvm_unreachable("shouldn't encounter string elements here");
3232 }
3233};
3234} // end anonymous namespace
3235
3236const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3237
3238/// Perform a compound assignment of LVal <op>= RVal.
3239static bool handleCompoundAssignment(
3240 EvalInfo &Info, const Expr *E,
3241 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3242 BinaryOperatorKind Opcode, const APValue &RVal) {
3243 if (LVal.Designator.Invalid)
3244 return false;
3245
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003246 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003247 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003248 return false;
3249 }
3250
3251 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3252 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3253 RVal };
3254 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3255}
3256
3257namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003258struct IncDecSubobjectHandler {
3259 EvalInfo &Info;
3260 const Expr *E;
3261 AccessKinds AccessKind;
3262 APValue *Old;
3263
3264 typedef bool result_type;
3265
3266 bool checkConst(QualType QT) {
3267 // Assigning to a const object has undefined behavior.
3268 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003269 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003270 return false;
3271 }
3272 return true;
3273 }
3274
3275 bool failed() { return false; }
3276 bool found(APValue &Subobj, QualType SubobjType) {
3277 // Stash the old value. Also clear Old, so we don't clobber it later
3278 // if we're post-incrementing a complex.
3279 if (Old) {
3280 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003281 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003282 }
3283
3284 switch (Subobj.getKind()) {
3285 case APValue::Int:
3286 return found(Subobj.getInt(), SubobjType);
3287 case APValue::Float:
3288 return found(Subobj.getFloat(), SubobjType);
3289 case APValue::ComplexInt:
3290 return found(Subobj.getComplexIntReal(),
3291 SubobjType->castAs<ComplexType>()->getElementType()
3292 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3293 case APValue::ComplexFloat:
3294 return found(Subobj.getComplexFloatReal(),
3295 SubobjType->castAs<ComplexType>()->getElementType()
3296 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3297 case APValue::LValue:
3298 return foundPointer(Subobj, SubobjType);
3299 default:
3300 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003301 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003302 return false;
3303 }
3304 }
3305 bool found(APSInt &Value, QualType SubobjType) {
3306 if (!checkConst(SubobjType))
3307 return false;
3308
3309 if (!SubobjType->isIntegerType()) {
3310 // We don't support increment / decrement on integer-cast-to-pointer
3311 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003312 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003313 return false;
3314 }
3315
3316 if (Old) *Old = APValue(Value);
3317
3318 // bool arithmetic promotes to int, and the conversion back to bool
3319 // doesn't reduce mod 2^n, so special-case it.
3320 if (SubobjType->isBooleanType()) {
3321 if (AccessKind == AK_Increment)
3322 Value = 1;
3323 else
3324 Value = !Value;
3325 return true;
3326 }
3327
3328 bool WasNegative = Value.isNegative();
3329 if (AccessKind == AK_Increment) {
3330 ++Value;
3331
3332 if (!WasNegative && Value.isNegative() &&
3333 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3334 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003335 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003336 }
3337 } else {
3338 --Value;
3339
3340 if (WasNegative && !Value.isNegative() &&
3341 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3342 unsigned BitWidth = Value.getBitWidth();
3343 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3344 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003345 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003346 }
3347 }
3348 return true;
3349 }
3350 bool found(APFloat &Value, QualType SubobjType) {
3351 if (!checkConst(SubobjType))
3352 return false;
3353
3354 if (Old) *Old = APValue(Value);
3355
3356 APFloat One(Value.getSemantics(), 1);
3357 if (AccessKind == AK_Increment)
3358 Value.add(One, APFloat::rmNearestTiesToEven);
3359 else
3360 Value.subtract(One, APFloat::rmNearestTiesToEven);
3361 return true;
3362 }
3363 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3364 if (!checkConst(SubobjType))
3365 return false;
3366
3367 QualType PointeeType;
3368 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3369 PointeeType = PT->getPointeeType();
3370 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003371 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003372 return false;
3373 }
3374
3375 LValue LVal;
3376 LVal.setFrom(Info.Ctx, Subobj);
3377 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3378 AccessKind == AK_Increment ? 1 : -1))
3379 return false;
3380 LVal.moveInto(Subobj);
3381 return true;
3382 }
3383 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3384 llvm_unreachable("shouldn't encounter string elements here");
3385 }
3386};
3387} // end anonymous namespace
3388
3389/// Perform an increment or decrement on LVal.
3390static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3391 QualType LValType, bool IsIncrement, APValue *Old) {
3392 if (LVal.Designator.Invalid)
3393 return false;
3394
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003395 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003396 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003397 return false;
3398 }
3399
3400 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3401 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3402 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3403 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3404}
3405
Richard Smithe97cbd72011-11-11 04:05:33 +00003406/// Build an lvalue for the object argument of a member function call.
3407static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3408 LValue &This) {
3409 if (Object->getType()->isPointerType())
3410 return EvaluatePointer(Object, This, Info);
3411
3412 if (Object->isGLValue())
3413 return EvaluateLValue(Object, This, Info);
3414
Richard Smithd9f663b2013-04-22 15:31:51 +00003415 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003416 return EvaluateTemporary(Object, This, Info);
3417
Faisal Valie690b7a2016-07-02 22:34:24 +00003418 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003419 return false;
3420}
3421
3422/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3423/// lvalue referring to the result.
3424///
3425/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003426/// \param LV - An lvalue referring to the base of the member pointer.
3427/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003428/// \param IncludeMember - Specifies whether the member itself is included in
3429/// the resulting LValue subobject designator. This is not possible when
3430/// creating a bound member function.
3431/// \return The field or method declaration to which the member pointer refers,
3432/// or 0 if evaluation fails.
3433static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003434 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003435 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003436 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003437 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003438 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003439 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003440 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003441
3442 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3443 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003444 if (!MemPtr.getDecl()) {
3445 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003446 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003447 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003448 }
Richard Smith253c2a32012-01-27 01:14:48 +00003449
Richard Smith027bf112011-11-17 22:56:20 +00003450 if (MemPtr.isDerivedMember()) {
3451 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003452 // The end of the derived-to-base path for the base object must match the
3453 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003454 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003455 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003456 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003457 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003458 }
Richard Smith027bf112011-11-17 22:56:20 +00003459 unsigned PathLengthToMember =
3460 LV.Designator.Entries.size() - MemPtr.Path.size();
3461 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3462 const CXXRecordDecl *LVDecl = getAsBaseClass(
3463 LV.Designator.Entries[PathLengthToMember + I]);
3464 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003465 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003466 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003467 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003468 }
Richard Smith027bf112011-11-17 22:56:20 +00003469 }
3470
3471 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003472 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003473 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003474 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003475 } else if (!MemPtr.Path.empty()) {
3476 // Extend the LValue path with the member pointer's path.
3477 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3478 MemPtr.Path.size() + IncludeMember);
3479
3480 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003481 if (const PointerType *PT = LVType->getAs<PointerType>())
3482 LVType = PT->getPointeeType();
3483 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3484 assert(RD && "member pointer access on non-class-type expression");
3485 // The first class in the path is that of the lvalue.
3486 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3487 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003488 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003489 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003490 RD = Base;
3491 }
3492 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003493 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3494 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003495 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003496 }
3497
3498 // Add the member. Note that we cannot build bound member functions here.
3499 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003500 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003501 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003502 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003503 } else if (const IndirectFieldDecl *IFD =
3504 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003505 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003506 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003507 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003508 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003509 }
Richard Smith027bf112011-11-17 22:56:20 +00003510 }
3511
3512 return MemPtr.getDecl();
3513}
3514
Richard Smith84401042013-06-03 05:03:02 +00003515static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3516 const BinaryOperator *BO,
3517 LValue &LV,
3518 bool IncludeMember = true) {
3519 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3520
3521 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003522 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003523 MemberPtr MemPtr;
3524 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3525 }
Craig Topper36250ad2014-05-12 05:36:57 +00003526 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003527 }
3528
3529 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3530 BO->getRHS(), IncludeMember);
3531}
3532
Richard Smith027bf112011-11-17 22:56:20 +00003533/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3534/// the provided lvalue, which currently refers to the base object.
3535static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3536 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003537 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003538 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003539 return false;
3540
Richard Smitha8105bc2012-01-06 16:39:00 +00003541 QualType TargetQT = E->getType();
3542 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3543 TargetQT = PT->getPointeeType();
3544
3545 // Check this cast lands within the final derived-to-base subobject path.
3546 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003547 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003548 << D.MostDerivedType << TargetQT;
3549 return false;
3550 }
3551
Richard Smith027bf112011-11-17 22:56:20 +00003552 // Check the type of the final cast. We don't need to check the path,
3553 // since a cast can only be formed if the path is unique.
3554 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003555 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3556 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003557 if (NewEntriesSize == D.MostDerivedPathLength)
3558 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3559 else
Richard Smith027bf112011-11-17 22:56:20 +00003560 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003561 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003562 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003563 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003564 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003565 }
Richard Smith027bf112011-11-17 22:56:20 +00003566
3567 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003568 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003569}
3570
Mike Stump876387b2009-10-27 22:09:17 +00003571namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003572enum EvalStmtResult {
3573 /// Evaluation failed.
3574 ESR_Failed,
3575 /// Hit a 'return' statement.
3576 ESR_Returned,
3577 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003578 ESR_Succeeded,
3579 /// Hit a 'continue' statement.
3580 ESR_Continue,
3581 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003582 ESR_Break,
3583 /// Still scanning for 'case' or 'default' statement.
3584 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003585};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003586}
Richard Smith254a73d2011-10-28 22:34:42 +00003587
Richard Smith97fcf4b2016-08-14 23:15:52 +00003588static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3589 // We don't need to evaluate the initializer for a static local.
3590 if (!VD->hasLocalStorage())
3591 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003592
Richard Smith97fcf4b2016-08-14 23:15:52 +00003593 LValue Result;
3594 Result.set(VD, Info.CurrentCall->Index);
3595 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003596
Richard Smith97fcf4b2016-08-14 23:15:52 +00003597 const Expr *InitE = VD->getInit();
3598 if (!InitE) {
3599 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3600 << false << VD->getType();
3601 Val = APValue();
3602 return false;
3603 }
Richard Smith51f03172013-06-20 03:00:05 +00003604
Richard Smith97fcf4b2016-08-14 23:15:52 +00003605 if (InitE->isValueDependent())
3606 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003607
Richard Smith97fcf4b2016-08-14 23:15:52 +00003608 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3609 // Wipe out any partially-computed value, to allow tracking that this
3610 // evaluation failed.
3611 Val = APValue();
3612 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003613 }
3614
3615 return true;
3616}
3617
Richard Smith97fcf4b2016-08-14 23:15:52 +00003618static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3619 bool OK = true;
3620
3621 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3622 OK &= EvaluateVarDecl(Info, VD);
3623
3624 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3625 for (auto *BD : DD->bindings())
3626 if (auto *VD = BD->getHoldingVar())
3627 OK &= EvaluateDecl(Info, VD);
3628
3629 return OK;
3630}
3631
3632
Richard Smith4e18ca52013-05-06 05:56:11 +00003633/// Evaluate a condition (either a variable declaration or an expression).
3634static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3635 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003636 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003637 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3638 return false;
3639 return EvaluateAsBooleanCondition(Cond, Result, Info);
3640}
3641
Richard Smith89210072016-04-04 23:29:43 +00003642namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003643/// \brief A location where the result (returned value) of evaluating a
3644/// statement should be stored.
3645struct StmtResult {
3646 /// The APValue that should be filled in with the returned value.
3647 APValue &Value;
3648 /// The location containing the result, if any (used to support RVO).
3649 const LValue *Slot;
3650};
Richard Smith89210072016-04-04 23:29:43 +00003651}
Richard Smith52a980a2015-08-28 02:43:42 +00003652
3653static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003654 const Stmt *S,
3655 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003656
3657/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003658static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003659 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003660 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003661 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003662 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003663 case ESR_Break:
3664 return ESR_Succeeded;
3665 case ESR_Succeeded:
3666 case ESR_Continue:
3667 return ESR_Continue;
3668 case ESR_Failed:
3669 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003670 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003671 return ESR;
3672 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003673 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003674}
3675
Richard Smith496ddcf2013-05-12 17:32:42 +00003676/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003677static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003678 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003679 BlockScopeRAII Scope(Info);
3680
Richard Smith496ddcf2013-05-12 17:32:42 +00003681 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003682 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003683 {
3684 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003685 if (const Stmt *Init = SS->getInit()) {
3686 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3687 if (ESR != ESR_Succeeded)
3688 return ESR;
3689 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003690 if (SS->getConditionVariable() &&
3691 !EvaluateDecl(Info, SS->getConditionVariable()))
3692 return ESR_Failed;
3693 if (!EvaluateInteger(SS->getCond(), Value, Info))
3694 return ESR_Failed;
3695 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003696
3697 // Find the switch case corresponding to the value of the condition.
3698 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003699 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003700 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3701 SC = SC->getNextSwitchCase()) {
3702 if (isa<DefaultStmt>(SC)) {
3703 Found = SC;
3704 continue;
3705 }
3706
3707 const CaseStmt *CS = cast<CaseStmt>(SC);
3708 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3709 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3710 : LHS;
3711 if (LHS <= Value && Value <= RHS) {
3712 Found = SC;
3713 break;
3714 }
3715 }
3716
3717 if (!Found)
3718 return ESR_Succeeded;
3719
3720 // Search the switch body for the switch case and evaluate it from there.
3721 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3722 case ESR_Break:
3723 return ESR_Succeeded;
3724 case ESR_Succeeded:
3725 case ESR_Continue:
3726 case ESR_Failed:
3727 case ESR_Returned:
3728 return ESR;
3729 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003730 // This can only happen if the switch case is nested within a statement
3731 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003732 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003733 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003734 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003735 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003736}
3737
Richard Smith254a73d2011-10-28 22:34:42 +00003738// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003739static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003740 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003741 if (!Info.nextStep(S))
3742 return ESR_Failed;
3743
Richard Smith496ddcf2013-05-12 17:32:42 +00003744 // If we're hunting down a 'case' or 'default' label, recurse through
3745 // substatements until we hit the label.
3746 if (Case) {
3747 // FIXME: We don't start the lifetime of objects whose initialization we
3748 // jump over. However, such objects must be of class type with a trivial
3749 // default constructor that initialize all subobjects, so must be empty,
3750 // so this almost never matters.
3751 switch (S->getStmtClass()) {
3752 case Stmt::CompoundStmtClass:
3753 // FIXME: Precompute which substatement of a compound statement we
3754 // would jump to, and go straight there rather than performing a
3755 // linear scan each time.
3756 case Stmt::LabelStmtClass:
3757 case Stmt::AttributedStmtClass:
3758 case Stmt::DoStmtClass:
3759 break;
3760
3761 case Stmt::CaseStmtClass:
3762 case Stmt::DefaultStmtClass:
3763 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003764 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003765 break;
3766
3767 case Stmt::IfStmtClass: {
3768 // FIXME: Precompute which side of an 'if' we would jump to, and go
3769 // straight there rather than scanning both sides.
3770 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003771
3772 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3773 // preceded by our switch label.
3774 BlockScopeRAII Scope(Info);
3775
Richard Smith496ddcf2013-05-12 17:32:42 +00003776 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3777 if (ESR != ESR_CaseNotFound || !IS->getElse())
3778 return ESR;
3779 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3780 }
3781
3782 case Stmt::WhileStmtClass: {
3783 EvalStmtResult ESR =
3784 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3785 if (ESR != ESR_Continue)
3786 return ESR;
3787 break;
3788 }
3789
3790 case Stmt::ForStmtClass: {
3791 const ForStmt *FS = cast<ForStmt>(S);
3792 EvalStmtResult ESR =
3793 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3794 if (ESR != ESR_Continue)
3795 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003796 if (FS->getInc()) {
3797 FullExpressionRAII IncScope(Info);
3798 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3799 return ESR_Failed;
3800 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003801 break;
3802 }
3803
3804 case Stmt::DeclStmtClass:
3805 // FIXME: If the variable has initialization that can't be jumped over,
3806 // bail out of any immediately-surrounding compound-statement too.
3807 default:
3808 return ESR_CaseNotFound;
3809 }
3810 }
3811
Richard Smith254a73d2011-10-28 22:34:42 +00003812 switch (S->getStmtClass()) {
3813 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003814 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003815 // Don't bother evaluating beyond an expression-statement which couldn't
3816 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003817 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003818 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003819 return ESR_Failed;
3820 return ESR_Succeeded;
3821 }
3822
Faisal Valie690b7a2016-07-02 22:34:24 +00003823 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003824 return ESR_Failed;
3825
3826 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003827 return ESR_Succeeded;
3828
Richard Smithd9f663b2013-04-22 15:31:51 +00003829 case Stmt::DeclStmtClass: {
3830 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003831 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003832 // Each declaration initialization is its own full-expression.
3833 // FIXME: This isn't quite right; if we're performing aggregate
3834 // initialization, each braced subexpression is its own full-expression.
3835 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003836 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003837 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003838 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003839 return ESR_Succeeded;
3840 }
3841
Richard Smith357362d2011-12-13 06:39:58 +00003842 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003843 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003844 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003845 if (RetExpr &&
3846 !(Result.Slot
3847 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3848 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003849 return ESR_Failed;
3850 return ESR_Returned;
3851 }
Richard Smith254a73d2011-10-28 22:34:42 +00003852
3853 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003854 BlockScopeRAII Scope(Info);
3855
Richard Smith254a73d2011-10-28 22:34:42 +00003856 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003857 for (const auto *BI : CS->body()) {
3858 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003859 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003860 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003861 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003862 return ESR;
3863 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003864 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003865 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003866
3867 case Stmt::IfStmtClass: {
3868 const IfStmt *IS = cast<IfStmt>(S);
3869
3870 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003871 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003872 if (const Stmt *Init = IS->getInit()) {
3873 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3874 if (ESR != ESR_Succeeded)
3875 return ESR;
3876 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003877 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003878 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003879 return ESR_Failed;
3880
3881 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3882 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3883 if (ESR != ESR_Succeeded)
3884 return ESR;
3885 }
3886 return ESR_Succeeded;
3887 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003888
3889 case Stmt::WhileStmtClass: {
3890 const WhileStmt *WS = cast<WhileStmt>(S);
3891 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003892 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003893 bool Continue;
3894 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3895 Continue))
3896 return ESR_Failed;
3897 if (!Continue)
3898 break;
3899
3900 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3901 if (ESR != ESR_Continue)
3902 return ESR;
3903 }
3904 return ESR_Succeeded;
3905 }
3906
3907 case Stmt::DoStmtClass: {
3908 const DoStmt *DS = cast<DoStmt>(S);
3909 bool Continue;
3910 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003911 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003912 if (ESR != ESR_Continue)
3913 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003914 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003915
Richard Smith08d6a2c2013-07-24 07:11:57 +00003916 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003917 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3918 return ESR_Failed;
3919 } while (Continue);
3920 return ESR_Succeeded;
3921 }
3922
3923 case Stmt::ForStmtClass: {
3924 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003925 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003926 if (FS->getInit()) {
3927 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3928 if (ESR != ESR_Succeeded)
3929 return ESR;
3930 }
3931 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003932 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003933 bool Continue = true;
3934 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3935 FS->getCond(), Continue))
3936 return ESR_Failed;
3937 if (!Continue)
3938 break;
3939
3940 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3941 if (ESR != ESR_Continue)
3942 return ESR;
3943
Richard Smith08d6a2c2013-07-24 07:11:57 +00003944 if (FS->getInc()) {
3945 FullExpressionRAII IncScope(Info);
3946 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3947 return ESR_Failed;
3948 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003949 }
3950 return ESR_Succeeded;
3951 }
3952
Richard Smith896e0d72013-05-06 06:51:17 +00003953 case Stmt::CXXForRangeStmtClass: {
3954 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003955 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003956
3957 // Initialize the __range variable.
3958 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3959 if (ESR != ESR_Succeeded)
3960 return ESR;
3961
3962 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003963 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3964 if (ESR != ESR_Succeeded)
3965 return ESR;
3966 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003967 if (ESR != ESR_Succeeded)
3968 return ESR;
3969
3970 while (true) {
3971 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003972 {
3973 bool Continue = true;
3974 FullExpressionRAII CondExpr(Info);
3975 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3976 return ESR_Failed;
3977 if (!Continue)
3978 break;
3979 }
Richard Smith896e0d72013-05-06 06:51:17 +00003980
3981 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003982 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003983 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3984 if (ESR != ESR_Succeeded)
3985 return ESR;
3986
3987 // Loop body.
3988 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3989 if (ESR != ESR_Continue)
3990 return ESR;
3991
3992 // Increment: ++__begin
3993 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3994 return ESR_Failed;
3995 }
3996
3997 return ESR_Succeeded;
3998 }
3999
Richard Smith496ddcf2013-05-12 17:32:42 +00004000 case Stmt::SwitchStmtClass:
4001 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4002
Richard Smith4e18ca52013-05-06 05:56:11 +00004003 case Stmt::ContinueStmtClass:
4004 return ESR_Continue;
4005
4006 case Stmt::BreakStmtClass:
4007 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004008
4009 case Stmt::LabelStmtClass:
4010 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4011
4012 case Stmt::AttributedStmtClass:
4013 // As a general principle, C++11 attributes can be ignored without
4014 // any semantic impact.
4015 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4016 Case);
4017
4018 case Stmt::CaseStmtClass:
4019 case Stmt::DefaultStmtClass:
4020 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004021 }
4022}
4023
Richard Smithcc36f692011-12-22 02:22:31 +00004024/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4025/// default constructor. If so, we'll fold it whether or not it's marked as
4026/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4027/// so we need special handling.
4028static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004029 const CXXConstructorDecl *CD,
4030 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004031 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4032 return false;
4033
Richard Smith66e05fe2012-01-18 05:21:49 +00004034 // Value-initialization does not call a trivial default constructor, so such a
4035 // call is a core constant expression whether or not the constructor is
4036 // constexpr.
4037 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004038 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004039 // FIXME: If DiagDecl is an implicitly-declared special member function,
4040 // we should be much more explicit about why it's not constexpr.
4041 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4042 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4043 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004044 } else {
4045 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4046 }
4047 }
4048 return true;
4049}
4050
Richard Smith357362d2011-12-13 06:39:58 +00004051/// CheckConstexprFunction - Check that a function can be called in a constant
4052/// expression.
4053static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4054 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004055 const FunctionDecl *Definition,
4056 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004057 // Potential constant expressions can contain calls to declared, but not yet
4058 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004059 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004060 Declaration->isConstexpr())
4061 return false;
4062
Richard Smith0838f3a2013-05-14 05:18:44 +00004063 // Bail out with no diagnostic if the function declaration itself is invalid.
4064 // We will have produced a relevant diagnostic while parsing it.
4065 if (Declaration->isInvalidDecl())
4066 return false;
4067
Richard Smith357362d2011-12-13 06:39:58 +00004068 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004069 if (Definition && Definition->isConstexpr() &&
4070 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004071 return true;
4072
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004073 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004074 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Faisal Valie690b7a2016-07-02 22:34:24 +00004075
Richard Smith5179eb72016-06-28 19:03:57 +00004076 // If this function is not constexpr because it is an inherited
4077 // non-constexpr constructor, diagnose that directly.
4078 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4079 if (CD && CD->isInheritingConstructor()) {
4080 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4081 if (!Inherited->isConstexpr())
4082 DiagDecl = CD = Inherited;
4083 }
4084
4085 // FIXME: If DiagDecl is an implicitly-declared special member function
4086 // or an inheriting constructor, we should be much more explicit about why
4087 // it's not constexpr.
4088 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004089 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004090 << CD->getInheritedConstructor().getConstructor()->getParent();
4091 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004092 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004093 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004094 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4095 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004096 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004097 }
4098 return false;
4099}
4100
Richard Smithbe6dd812014-11-19 21:27:17 +00004101/// Determine if a class has any fields that might need to be copied by a
4102/// trivial copy or move operation.
4103static bool hasFields(const CXXRecordDecl *RD) {
4104 if (!RD || RD->isEmpty())
4105 return false;
4106 for (auto *FD : RD->fields()) {
4107 if (FD->isUnnamedBitfield())
4108 continue;
4109 return true;
4110 }
4111 for (auto &Base : RD->bases())
4112 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4113 return true;
4114 return false;
4115}
4116
Richard Smithd62306a2011-11-10 06:34:14 +00004117namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004118typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004119}
4120
4121/// EvaluateArgs - Evaluate the arguments to a function call.
4122static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4123 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004124 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004125 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004126 I != E; ++I) {
4127 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4128 // If we're checking for a potential constant expression, evaluate all
4129 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004130 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004131 return false;
4132 Success = false;
4133 }
4134 }
4135 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004136}
4137
Richard Smith254a73d2011-10-28 22:34:42 +00004138/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004139static bool HandleFunctionCall(SourceLocation CallLoc,
4140 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004141 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004142 EvalInfo &Info, APValue &Result,
4143 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004144 ArgVector ArgValues(Args.size());
4145 if (!EvaluateArgs(Args, ArgValues, Info))
4146 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004147
Richard Smith253c2a32012-01-27 01:14:48 +00004148 if (!Info.CheckCallLimit(CallLoc))
4149 return false;
4150
4151 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004152
4153 // For a trivial copy or move assignment, perform an APValue copy. This is
4154 // essential for unions, where the operations performed by the assignment
4155 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004156 //
4157 // Skip this for non-union classes with no fields; in that case, the defaulted
4158 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004159 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004160 if (MD && MD->isDefaulted() &&
4161 (MD->getParent()->isUnion() ||
4162 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004163 assert(This &&
4164 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4165 LValue RHS;
4166 RHS.setFrom(Info.Ctx, ArgValues[0]);
4167 APValue RHSValue;
4168 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4169 RHS, RHSValue))
4170 return false;
4171 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4172 RHSValue))
4173 return false;
4174 This->moveInto(Result);
4175 return true;
4176 }
4177
Richard Smith52a980a2015-08-28 02:43:42 +00004178 StmtResult Ret = {Result, ResultSlot};
4179 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004180 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004181 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004182 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004183 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004184 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004185 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004186}
4187
Richard Smithd62306a2011-11-10 06:34:14 +00004188/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004189static bool HandleConstructorCall(const Expr *E, const LValue &This,
4190 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004191 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004192 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004193 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004194 if (!Info.CheckCallLimit(CallLoc))
4195 return false;
4196
Richard Smith3607ffe2012-02-13 03:54:03 +00004197 const CXXRecordDecl *RD = Definition->getParent();
4198 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004199 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004200 return false;
4201 }
4202
Richard Smith5179eb72016-06-28 19:03:57 +00004203 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004204
Richard Smith52a980a2015-08-28 02:43:42 +00004205 // FIXME: Creating an APValue just to hold a nonexistent return value is
4206 // wasteful.
4207 APValue RetVal;
4208 StmtResult Ret = {RetVal, nullptr};
4209
Richard Smith5179eb72016-06-28 19:03:57 +00004210 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004211 if (Definition->isDelegatingConstructor()) {
4212 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004213 {
4214 FullExpressionRAII InitScope(Info);
4215 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4216 return false;
4217 }
Richard Smith52a980a2015-08-28 02:43:42 +00004218 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004219 }
4220
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004221 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004222 // essential for unions (or classes with anonymous union members), where the
4223 // operations performed by the constructor cannot be represented by
4224 // ctor-initializers.
4225 //
4226 // Skip this for empty non-union classes; we should not perform an
4227 // lvalue-to-rvalue conversion on them because their copy constructor does not
4228 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004229 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004230 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004231 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004232 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004233 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004234 return handleLValueToRValueConversion(
4235 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4236 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004237 }
4238
4239 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004240 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004241 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004242 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004243
John McCalld7bca762012-05-01 00:38:49 +00004244 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004245 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4246
Richard Smith08d6a2c2013-07-24 07:11:57 +00004247 // A scope for temporaries lifetime-extended by reference members.
4248 BlockScopeRAII LifetimeExtendedScope(Info);
4249
Richard Smith253c2a32012-01-27 01:14:48 +00004250 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004251 unsigned BasesSeen = 0;
4252#ifndef NDEBUG
4253 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4254#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004255 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004256 LValue Subobject = This;
4257 APValue *Value = &Result;
4258
4259 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004260 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004261 if (I->isBaseInitializer()) {
4262 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004263#ifndef NDEBUG
4264 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004265 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004266 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4267 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4268 "base class initializers not in expected order");
4269 ++BaseIt;
4270#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004271 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004272 BaseType->getAsCXXRecordDecl(), &Layout))
4273 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004274 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004275 } else if ((FD = I->getMember())) {
4276 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004277 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004278 if (RD->isUnion()) {
4279 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004280 Value = &Result.getUnionValue();
4281 } else {
4282 Value = &Result.getStructField(FD->getFieldIndex());
4283 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004284 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004285 // Walk the indirect field decl's chain to find the object to initialize,
4286 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004287 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004288 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004289 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4290 // Switch the union field if it differs. This happens if we had
4291 // preceding zero-initialization, and we're now initializing a union
4292 // subobject other than the first.
4293 // FIXME: In this case, the values of the other subobjects are
4294 // specified, since zero-initialization sets all padding bits to zero.
4295 if (Value->isUninit() ||
4296 (Value->isUnion() && Value->getUnionField() != FD)) {
4297 if (CD->isUnion())
4298 *Value = APValue(FD);
4299 else
4300 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004301 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004302 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004303 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004304 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004305 if (CD->isUnion())
4306 Value = &Value->getUnionValue();
4307 else
4308 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004309 }
Richard Smithd62306a2011-11-10 06:34:14 +00004310 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004311 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004312 }
Richard Smith253c2a32012-01-27 01:14:48 +00004313
Richard Smith08d6a2c2013-07-24 07:11:57 +00004314 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004315 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4316 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004317 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004318 // If we're checking for a potential constant expression, evaluate all
4319 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004320 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004321 return false;
4322 Success = false;
4323 }
Richard Smithd62306a2011-11-10 06:34:14 +00004324 }
4325
Richard Smithd9f663b2013-04-22 15:31:51 +00004326 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004327 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004328}
4329
Richard Smith5179eb72016-06-28 19:03:57 +00004330static bool HandleConstructorCall(const Expr *E, const LValue &This,
4331 ArrayRef<const Expr*> Args,
4332 const CXXConstructorDecl *Definition,
4333 EvalInfo &Info, APValue &Result) {
4334 ArgVector ArgValues(Args.size());
4335 if (!EvaluateArgs(Args, ArgValues, Info))
4336 return false;
4337
4338 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4339 Info, Result);
4340}
4341
Eli Friedman9a156e52008-11-12 09:44:48 +00004342//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004343// Generic Evaluation
4344//===----------------------------------------------------------------------===//
4345namespace {
4346
Aaron Ballman68af21c2014-01-03 19:26:43 +00004347template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004348class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004349 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004350private:
Richard Smith52a980a2015-08-28 02:43:42 +00004351 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004352 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004353 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004354 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004355 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004356 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004357 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004358
Richard Smith17100ba2012-02-16 02:46:34 +00004359 // Check whether a conditional operator with a non-constant condition is a
4360 // potential constant expression. If neither arm is a potential constant
4361 // expression, then the conditional operator is not either.
4362 template<typename ConditionalOperator>
4363 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004364 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004365
4366 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004367 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004368 {
Richard Smith17100ba2012-02-16 02:46:34 +00004369 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004370 StmtVisitorTy::Visit(E->getFalseExpr());
4371 if (Diag.empty())
4372 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004373 }
Richard Smith17100ba2012-02-16 02:46:34 +00004374
George Burgess IV8c892b52016-05-25 22:31:54 +00004375 {
4376 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004377 Diag.clear();
4378 StmtVisitorTy::Visit(E->getTrueExpr());
4379 if (Diag.empty())
4380 return;
4381 }
4382
4383 Error(E, diag::note_constexpr_conditional_never_const);
4384 }
4385
4386
4387 template<typename ConditionalOperator>
4388 bool HandleConditionalOperator(const ConditionalOperator *E) {
4389 bool BoolResult;
4390 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004391 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004392 CheckPotentialConstantConditional(E);
4393 return false;
4394 }
4395
4396 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4397 return StmtVisitorTy::Visit(EvalExpr);
4398 }
4399
Peter Collingbournee9200682011-05-13 03:29:01 +00004400protected:
4401 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004402 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004403 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4404
Richard Smith92b1ce02011-12-12 09:28:41 +00004405 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004406 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004407 }
4408
Aaron Ballman68af21c2014-01-03 19:26:43 +00004409 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004410
4411public:
4412 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4413
4414 EvalInfo &getEvalInfo() { return Info; }
4415
Richard Smithf57d8cb2011-12-09 22:58:01 +00004416 /// Report an evaluation error. This should only be called when an error is
4417 /// first discovered. When propagating an error, just return false.
4418 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004419 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004420 return false;
4421 }
4422 bool Error(const Expr *E) {
4423 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4424 }
4425
Aaron Ballman68af21c2014-01-03 19:26:43 +00004426 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004427 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004428 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004429 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004430 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004431 }
4432
Aaron Ballman68af21c2014-01-03 19:26:43 +00004433 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004434 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004435 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004436 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004437 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004438 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004439 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004440 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004441 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004442 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004443 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004444 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004445 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004446 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004447 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004448 // The initializer may not have been parsed yet, or might be erroneous.
4449 if (!E->getExpr())
4450 return Error(E);
4451 return StmtVisitorTy::Visit(E->getExpr());
4452 }
Richard Smith5894a912011-12-19 22:12:41 +00004453 // We cannot create any objects for which cleanups are required, so there is
4454 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004455 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004456 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004457
Aaron Ballman68af21c2014-01-03 19:26:43 +00004458 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004459 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4460 return static_cast<Derived*>(this)->VisitCastExpr(E);
4461 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004462 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004463 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4464 return static_cast<Derived*>(this)->VisitCastExpr(E);
4465 }
4466
Aaron Ballman68af21c2014-01-03 19:26:43 +00004467 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004468 switch (E->getOpcode()) {
4469 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004470 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004471
4472 case BO_Comma:
4473 VisitIgnoredValue(E->getLHS());
4474 return StmtVisitorTy::Visit(E->getRHS());
4475
4476 case BO_PtrMemD:
4477 case BO_PtrMemI: {
4478 LValue Obj;
4479 if (!HandleMemberPointerAccess(Info, E, Obj))
4480 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004481 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004482 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004483 return false;
4484 return DerivedSuccess(Result, E);
4485 }
4486 }
4487 }
4488
Aaron Ballman68af21c2014-01-03 19:26:43 +00004489 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004490 // Evaluate and cache the common expression. We treat it as a temporary,
4491 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004492 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004493 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004494 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004495
Richard Smith17100ba2012-02-16 02:46:34 +00004496 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004497 }
4498
Aaron Ballman68af21c2014-01-03 19:26:43 +00004499 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004500 bool IsBcpCall = false;
4501 // If the condition (ignoring parens) is a __builtin_constant_p call,
4502 // the result is a constant expression if it can be folded without
4503 // side-effects. This is an important GNU extension. See GCC PR38377
4504 // for discussion.
4505 if (const CallExpr *CallCE =
4506 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004507 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004508 IsBcpCall = true;
4509
4510 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4511 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004512 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004513 return false;
4514
Richard Smith6d4c6582013-11-05 22:18:15 +00004515 FoldConstant Fold(Info, IsBcpCall);
4516 if (!HandleConditionalOperator(E)) {
4517 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004518 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004519 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004520
4521 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004522 }
4523
Aaron Ballman68af21c2014-01-03 19:26:43 +00004524 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004525 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4526 return DerivedSuccess(*Value, E);
4527
4528 const Expr *Source = E->getSourceExpr();
4529 if (!Source)
4530 return Error(E);
4531 if (Source == E) { // sanity checking.
4532 assert(0 && "OpaqueValueExpr recursively refers to itself");
4533 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004534 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004535 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004536 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004537
Aaron Ballman68af21c2014-01-03 19:26:43 +00004538 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004539 APValue Result;
4540 if (!handleCallExpr(E, Result, nullptr))
4541 return false;
4542 return DerivedSuccess(Result, E);
4543 }
4544
4545 bool handleCallExpr(const CallExpr *E, APValue &Result,
4546 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004547 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004548 QualType CalleeType = Callee->getType();
4549
Craig Topper36250ad2014-05-12 05:36:57 +00004550 const FunctionDecl *FD = nullptr;
4551 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004552 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004553 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004554
Richard Smithe97cbd72011-11-11 04:05:33 +00004555 // Extract function decl and 'this' pointer from the callee.
4556 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004557 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004558 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4559 // Explicit bound member calls, such as x.f() or p->g();
4560 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004561 return false;
4562 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004563 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004564 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004565 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4566 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004567 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4568 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004569 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004570 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004571 return Error(Callee);
4572
4573 FD = dyn_cast<FunctionDecl>(Member);
4574 if (!FD)
4575 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004576 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004577 LValue Call;
4578 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004579 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004580
Richard Smitha8105bc2012-01-06 16:39:00 +00004581 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004582 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004583 FD = dyn_cast_or_null<FunctionDecl>(
4584 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004585 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004586 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004587 // Don't call function pointers which have been cast to some other type.
4588 // Per DR (no number yet), the caller and callee can differ in noexcept.
4589 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4590 CalleeType->getPointeeType(), FD->getType())) {
4591 return Error(E);
4592 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004593
4594 // Overloaded operator calls to member functions are represented as normal
4595 // calls with '*this' as the first argument.
4596 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4597 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004598 // FIXME: When selecting an implicit conversion for an overloaded
4599 // operator delete, we sometimes try to evaluate calls to conversion
4600 // operators without a 'this' parameter!
4601 if (Args.empty())
4602 return Error(E);
4603
Richard Smithe97cbd72011-11-11 04:05:33 +00004604 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4605 return false;
4606 This = &ThisVal;
4607 Args = Args.slice(1);
Faisal Valid92e7492017-01-08 18:56:11 +00004608 } else if (MD && MD->isLambdaStaticInvoker()) {
4609 // Map the static invoker for the lambda back to the call operator.
4610 // Conveniently, we don't have to slice out the 'this' argument (as is
4611 // being done for the non-static case), since a static member function
4612 // doesn't have an implicit argument passed in.
4613 const CXXRecordDecl *ClosureClass = MD->getParent();
4614 assert(
4615 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4616 "Number of captures must be zero for conversion to function-ptr");
4617
4618 const CXXMethodDecl *LambdaCallOp =
4619 ClosureClass->getLambdaCallOperator();
4620
4621 // Set 'FD', the function that will be called below, to the call
4622 // operator. If the closure object represents a generic lambda, find
4623 // the corresponding specialization of the call operator.
4624
4625 if (ClosureClass->isGenericLambda()) {
4626 assert(MD->isFunctionTemplateSpecialization() &&
4627 "A generic lambda's static-invoker function must be a "
4628 "template specialization");
4629 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4630 FunctionTemplateDecl *CallOpTemplate =
4631 LambdaCallOp->getDescribedFunctionTemplate();
4632 void *InsertPos = nullptr;
4633 FunctionDecl *CorrespondingCallOpSpecialization =
4634 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4635 assert(CorrespondingCallOpSpecialization &&
4636 "We must always have a function call operator specialization "
4637 "that corresponds to our static invoker specialization");
4638 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4639 } else
4640 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004641 }
4642
Faisal Valid92e7492017-01-08 18:56:11 +00004643
Richard Smithe97cbd72011-11-11 04:05:33 +00004644 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004645 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004646
Richard Smith47b34932012-02-01 02:39:43 +00004647 if (This && !This->checkSubobject(Info, E, CSK_This))
4648 return false;
4649
Richard Smith3607ffe2012-02-13 03:54:03 +00004650 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4651 // calls to such functions in constant expressions.
4652 if (This && !HasQualifier &&
4653 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4654 return Error(E, diag::note_constexpr_virtual_call);
4655
Craig Topper36250ad2014-05-12 05:36:57 +00004656 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004657 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004658
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004659 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004660 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4661 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004662 return false;
4663
Richard Smith52a980a2015-08-28 02:43:42 +00004664 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004665 }
4666
Aaron Ballman68af21c2014-01-03 19:26:43 +00004667 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004668 return StmtVisitorTy::Visit(E->getInitializer());
4669 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004670 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004671 if (E->getNumInits() == 0)
4672 return DerivedZeroInitialization(E);
4673 if (E->getNumInits() == 1)
4674 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004675 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004676 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004677 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004678 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004679 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004680 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004681 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004682 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004683 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004684 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004685 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004686
Richard Smithd62306a2011-11-10 06:34:14 +00004687 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004688 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004689 assert(!E->isArrow() && "missing call to bound member function?");
4690
Richard Smith2e312c82012-03-03 22:46:17 +00004691 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004692 if (!Evaluate(Val, Info, E->getBase()))
4693 return false;
4694
4695 QualType BaseTy = E->getBase()->getType();
4696
4697 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004698 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004699 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004700 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004701 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4702
Richard Smith3229b742013-05-05 21:17:10 +00004703 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004704 SubobjectDesignator Designator(BaseTy);
4705 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004706
Richard Smith3229b742013-05-05 21:17:10 +00004707 APValue Result;
4708 return extractSubobject(Info, E, Obj, Designator, Result) &&
4709 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004710 }
4711
Aaron Ballman68af21c2014-01-03 19:26:43 +00004712 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004713 switch (E->getCastKind()) {
4714 default:
4715 break;
4716
Richard Smitha23ab512013-05-23 00:30:41 +00004717 case CK_AtomicToNonAtomic: {
4718 APValue AtomicVal;
4719 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4720 return false;
4721 return DerivedSuccess(AtomicVal, E);
4722 }
4723
Richard Smith11562c52011-10-28 17:51:58 +00004724 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004725 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004726 return StmtVisitorTy::Visit(E->getSubExpr());
4727
4728 case CK_LValueToRValue: {
4729 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004730 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4731 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004732 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004733 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004734 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004735 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004736 return false;
4737 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004738 }
4739 }
4740
Richard Smithf57d8cb2011-12-09 22:58:01 +00004741 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004742 }
4743
Aaron Ballman68af21c2014-01-03 19:26:43 +00004744 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004745 return VisitUnaryPostIncDec(UO);
4746 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004747 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004748 return VisitUnaryPostIncDec(UO);
4749 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004750 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004751 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004752 return Error(UO);
4753
4754 LValue LVal;
4755 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4756 return false;
4757 APValue RVal;
4758 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4759 UO->isIncrementOp(), &RVal))
4760 return false;
4761 return DerivedSuccess(RVal, UO);
4762 }
4763
Aaron Ballman68af21c2014-01-03 19:26:43 +00004764 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004765 // We will have checked the full-expressions inside the statement expression
4766 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004767 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004768 return Error(E);
4769
Richard Smith08d6a2c2013-07-24 07:11:57 +00004770 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004771 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004772 if (CS->body_empty())
4773 return true;
4774
Richard Smith51f03172013-06-20 03:00:05 +00004775 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4776 BE = CS->body_end();
4777 /**/; ++BI) {
4778 if (BI + 1 == BE) {
4779 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4780 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004781 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004782 diag::note_constexpr_stmt_expr_unsupported);
4783 return false;
4784 }
4785 return this->Visit(FinalExpr);
4786 }
4787
4788 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004789 StmtResult Result = { ReturnValue, nullptr };
4790 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004791 if (ESR != ESR_Succeeded) {
4792 // FIXME: If the statement-expression terminated due to 'return',
4793 // 'break', or 'continue', it would be nice to propagate that to
4794 // the outer statement evaluation rather than bailing out.
4795 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004796 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004797 diag::note_constexpr_stmt_expr_unsupported);
4798 return false;
4799 }
4800 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004801
4802 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004803 }
4804
Richard Smith4a678122011-10-24 18:44:57 +00004805 /// Visit a value which is evaluated, but whose value is ignored.
4806 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004807 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004808 }
David Majnemere9807b22016-02-26 04:23:19 +00004809
4810 /// Potentially visit a MemberExpr's base expression.
4811 void VisitIgnoredBaseExpression(const Expr *E) {
4812 // While MSVC doesn't evaluate the base expression, it does diagnose the
4813 // presence of side-effecting behavior.
4814 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4815 return;
4816 VisitIgnoredValue(E);
4817 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004818};
4819
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004820}
Peter Collingbournee9200682011-05-13 03:29:01 +00004821
4822//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004823// Common base class for lvalue and temporary evaluation.
4824//===----------------------------------------------------------------------===//
4825namespace {
4826template<class Derived>
4827class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004828 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004829protected:
4830 LValue &Result;
4831 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004832 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004833
4834 bool Success(APValue::LValueBase B) {
4835 Result.set(B);
4836 return true;
4837 }
4838
4839public:
4840 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4841 ExprEvaluatorBaseTy(Info), Result(Result) {}
4842
Richard Smith2e312c82012-03-03 22:46:17 +00004843 bool Success(const APValue &V, const Expr *E) {
4844 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004845 return true;
4846 }
Richard Smith027bf112011-11-17 22:56:20 +00004847
Richard Smith027bf112011-11-17 22:56:20 +00004848 bool VisitMemberExpr(const MemberExpr *E) {
4849 // Handle non-static data members.
4850 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004851 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004852 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004853 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004854 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004855 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004856 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004857 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004858 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004859 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004860 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004861 BaseTy = E->getBase()->getType();
4862 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004863 if (!EvalOK) {
4864 if (!this->Info.allowInvalidBaseExpr())
4865 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004866 Result.setInvalid(E);
4867 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004868 }
Richard Smith027bf112011-11-17 22:56:20 +00004869
Richard Smith1b78b3d2012-01-25 22:15:11 +00004870 const ValueDecl *MD = E->getMemberDecl();
4871 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4872 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4873 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4874 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004875 if (!HandleLValueMember(this->Info, E, Result, FD))
4876 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004877 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004878 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4879 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004880 } else
4881 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004882
Richard Smith1b78b3d2012-01-25 22:15:11 +00004883 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004884 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004885 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004886 RefValue))
4887 return false;
4888 return Success(RefValue, E);
4889 }
4890 return true;
4891 }
4892
4893 bool VisitBinaryOperator(const BinaryOperator *E) {
4894 switch (E->getOpcode()) {
4895 default:
4896 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4897
4898 case BO_PtrMemD:
4899 case BO_PtrMemI:
4900 return HandleMemberPointerAccess(this->Info, E, Result);
4901 }
4902 }
4903
4904 bool VisitCastExpr(const CastExpr *E) {
4905 switch (E->getCastKind()) {
4906 default:
4907 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4908
4909 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004910 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004911 if (!this->Visit(E->getSubExpr()))
4912 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004913
4914 // Now figure out the necessary offset to add to the base LV to get from
4915 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004916 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4917 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004918 }
4919 }
4920};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004921}
Richard Smith027bf112011-11-17 22:56:20 +00004922
4923//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004924// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004925//
4926// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4927// function designators (in C), decl references to void objects (in C), and
4928// temporaries (if building with -Wno-address-of-temporary).
4929//
4930// LValue evaluation produces values comprising a base expression of one of the
4931// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004932// - Declarations
4933// * VarDecl
4934// * FunctionDecl
4935// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00004936// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00004937// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004938// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004939// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004940// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004941// * ObjCEncodeExpr
4942// * AddrLabelExpr
4943// * BlockExpr
4944// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004945// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004946// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004947// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004948// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4949// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004950// * A MaterializeTemporaryExpr that has static storage duration, with no
4951// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004952// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004953//===----------------------------------------------------------------------===//
4954namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004955class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004956 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004957public:
Richard Smith027bf112011-11-17 22:56:20 +00004958 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4959 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004960
Richard Smith11562c52011-10-28 17:51:58 +00004961 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004962 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004963
Peter Collingbournee9200682011-05-13 03:29:01 +00004964 bool VisitDeclRefExpr(const DeclRefExpr *E);
4965 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004966 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004967 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4968 bool VisitMemberExpr(const MemberExpr *E);
4969 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4970 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004971 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004972 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004973 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4974 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004975 bool VisitUnaryReal(const UnaryOperator *E);
4976 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004977 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4978 return VisitUnaryPreIncDec(UO);
4979 }
4980 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4981 return VisitUnaryPreIncDec(UO);
4982 }
Richard Smith3229b742013-05-05 21:17:10 +00004983 bool VisitBinAssign(const BinaryOperator *BO);
4984 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004985
Peter Collingbournee9200682011-05-13 03:29:01 +00004986 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004987 switch (E->getCastKind()) {
4988 default:
Richard Smith027bf112011-11-17 22:56:20 +00004989 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004990
Eli Friedmance3e02a2011-10-11 00:13:24 +00004991 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004992 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004993 if (!Visit(E->getSubExpr()))
4994 return false;
4995 Result.Designator.setInvalid();
4996 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004997
Richard Smith027bf112011-11-17 22:56:20 +00004998 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004999 if (!Visit(E->getSubExpr()))
5000 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005001 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005002 }
5003 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005004};
5005} // end anonymous namespace
5006
Richard Smith11562c52011-10-28 17:51:58 +00005007/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005008/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005009/// * function designators in C, and
5010/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005011/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00005012static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
5013 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005014 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00005015 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005016}
5017
Peter Collingbournee9200682011-05-13 03:29:01 +00005018bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005019 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005020 return Success(FD);
5021 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005022 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005023 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005024 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005025 return Error(E);
5026}
Richard Smith733237d2011-10-24 23:14:33 +00005027
Faisal Vali0528a312016-11-13 06:09:16 +00005028
Richard Smith11562c52011-10-28 17:51:58 +00005029bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00005030 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005031 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5032 // Only if a local variable was declared in the function currently being
5033 // evaluated, do we expect to be able to find its value in the current
5034 // frame. (Otherwise it was likely declared in an enclosing context and
5035 // could either have a valid evaluatable value (for e.g. a constexpr
5036 // variable) or be ill-formed (and trigger an appropriate evaluation
5037 // diagnostic)).
5038 if (Info.CurrentCall->Callee &&
5039 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5040 Frame = Info.CurrentCall;
5041 }
5042 }
Richard Smith3229b742013-05-05 21:17:10 +00005043
Richard Smithfec09922011-11-01 16:57:24 +00005044 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005045 if (Frame) {
5046 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005047 return true;
5048 }
Richard Smithce40ad62011-11-12 22:28:03 +00005049 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005050 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005051
Richard Smith3229b742013-05-05 21:17:10 +00005052 APValue *V;
5053 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005054 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005055 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005056 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005057 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005058 return false;
5059 }
Richard Smith3229b742013-05-05 21:17:10 +00005060 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005061}
5062
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005063bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5064 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005065 // Walk through the expression to find the materialized temporary itself.
5066 SmallVector<const Expr *, 2> CommaLHSs;
5067 SmallVector<SubobjectAdjustment, 2> Adjustments;
5068 const Expr *Inner = E->GetTemporaryExpr()->
5069 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005070
Richard Smith84401042013-06-03 05:03:02 +00005071 // If we passed any comma operators, evaluate their LHSs.
5072 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5073 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5074 return false;
5075
Richard Smithe6c01442013-06-05 00:46:14 +00005076 // A materialized temporary with static storage duration can appear within the
5077 // result of a constant expression evaluation, so we need to preserve its
5078 // value for use outside this evaluation.
5079 APValue *Value;
5080 if (E->getStorageDuration() == SD_Static) {
5081 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005082 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005083 Result.set(E);
5084 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005085 Value = &Info.CurrentCall->
5086 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005087 Result.set(E, Info.CurrentCall->Index);
5088 }
5089
Richard Smithea4ad5d2013-06-06 08:19:16 +00005090 QualType Type = Inner->getType();
5091
Richard Smith84401042013-06-03 05:03:02 +00005092 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005093 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5094 (E->getStorageDuration() == SD_Static &&
5095 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5096 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005097 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005098 }
Richard Smith84401042013-06-03 05:03:02 +00005099
5100 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005101 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5102 --I;
5103 switch (Adjustments[I].Kind) {
5104 case SubobjectAdjustment::DerivedToBaseAdjustment:
5105 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5106 Type, Result))
5107 return false;
5108 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5109 break;
5110
5111 case SubobjectAdjustment::FieldAdjustment:
5112 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5113 return false;
5114 Type = Adjustments[I].Field->getType();
5115 break;
5116
5117 case SubobjectAdjustment::MemberPointerAdjustment:
5118 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5119 Adjustments[I].Ptr.RHS))
5120 return false;
5121 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5122 break;
5123 }
5124 }
5125
5126 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005127}
5128
Peter Collingbournee9200682011-05-13 03:29:01 +00005129bool
5130LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005131 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5132 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005133 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5134 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005135 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005136}
5137
Richard Smith6e525142011-12-27 12:18:28 +00005138bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005139 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005140 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005141
Faisal Valie690b7a2016-07-02 22:34:24 +00005142 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005143 << E->getExprOperand()->getType()
5144 << E->getExprOperand()->getSourceRange();
5145 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005146}
5147
Francois Pichet0066db92012-04-16 04:08:35 +00005148bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5149 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005150}
Francois Pichet0066db92012-04-16 04:08:35 +00005151
Peter Collingbournee9200682011-05-13 03:29:01 +00005152bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005153 // Handle static data members.
5154 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005155 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005156 return VisitVarDecl(E, VD);
5157 }
5158
Richard Smith254a73d2011-10-28 22:34:42 +00005159 // Handle static member functions.
5160 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5161 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005162 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005163 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005164 }
5165 }
5166
Richard Smithd62306a2011-11-10 06:34:14 +00005167 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005168 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005169}
5170
Peter Collingbournee9200682011-05-13 03:29:01 +00005171bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005172 // FIXME: Deal with vectors as array subscript bases.
5173 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005174 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005175
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005176 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00005177 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005178
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005179 APSInt Index;
5180 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005181 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005182
Richard Smithd6cc1982017-01-31 02:23:02 +00005183 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005184}
Eli Friedman9a156e52008-11-12 09:44:48 +00005185
Peter Collingbournee9200682011-05-13 03:29:01 +00005186bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00005187 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005188}
5189
Richard Smith66c96992012-02-18 22:04:06 +00005190bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5191 if (!Visit(E->getSubExpr()))
5192 return false;
5193 // __real is a no-op on scalar lvalues.
5194 if (E->getSubExpr()->getType()->isAnyComplexType())
5195 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5196 return true;
5197}
5198
5199bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5200 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5201 "lvalue __imag__ on scalar?");
5202 if (!Visit(E->getSubExpr()))
5203 return false;
5204 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5205 return true;
5206}
5207
Richard Smith243ef902013-05-05 23:31:59 +00005208bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005209 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005210 return Error(UO);
5211
5212 if (!this->Visit(UO->getSubExpr()))
5213 return false;
5214
Richard Smith243ef902013-05-05 23:31:59 +00005215 return handleIncDec(
5216 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005217 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005218}
5219
5220bool LValueExprEvaluator::VisitCompoundAssignOperator(
5221 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005222 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005223 return Error(CAO);
5224
Richard Smith3229b742013-05-05 21:17:10 +00005225 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005226
5227 // The overall lvalue result is the result of evaluating the LHS.
5228 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005229 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005230 Evaluate(RHS, this->Info, CAO->getRHS());
5231 return false;
5232 }
5233
Richard Smith3229b742013-05-05 21:17:10 +00005234 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5235 return false;
5236
Richard Smith43e77732013-05-07 04:50:00 +00005237 return handleCompoundAssignment(
5238 this->Info, CAO,
5239 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5240 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005241}
5242
5243bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005244 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005245 return Error(E);
5246
Richard Smith3229b742013-05-05 21:17:10 +00005247 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005248
5249 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005250 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005251 Evaluate(NewVal, this->Info, E->getRHS());
5252 return false;
5253 }
5254
Richard Smith3229b742013-05-05 21:17:10 +00005255 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5256 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005257
5258 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005259 NewVal);
5260}
5261
Eli Friedman9a156e52008-11-12 09:44:48 +00005262//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005263// Pointer Evaluation
5264//===----------------------------------------------------------------------===//
5265
George Burgess IVe3763372016-12-22 02:50:20 +00005266/// \brief Attempts to compute the number of bytes available at the pointer
5267/// returned by a function with the alloc_size attribute. Returns true if we
5268/// were successful. Places an unsigned number into `Result`.
5269///
5270/// This expects the given CallExpr to be a call to a function with an
5271/// alloc_size attribute.
5272static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5273 const CallExpr *Call,
5274 llvm::APInt &Result) {
5275 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5276
5277 // alloc_size args are 1-indexed, 0 means not present.
5278 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5279 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5280 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5281 if (Call->getNumArgs() <= SizeArgNo)
5282 return false;
5283
5284 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5285 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5286 return false;
5287 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5288 return false;
5289 Into = Into.zextOrSelf(BitsInSizeT);
5290 return true;
5291 };
5292
5293 APSInt SizeOfElem;
5294 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5295 return false;
5296
5297 if (!AllocSize->getNumElemsParam()) {
5298 Result = std::move(SizeOfElem);
5299 return true;
5300 }
5301
5302 APSInt NumberOfElems;
5303 // Argument numbers start at 1
5304 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5305 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5306 return false;
5307
5308 bool Overflow;
5309 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5310 if (Overflow)
5311 return false;
5312
5313 Result = std::move(BytesAvailable);
5314 return true;
5315}
5316
5317/// \brief Convenience function. LVal's base must be a call to an alloc_size
5318/// function.
5319static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5320 const LValue &LVal,
5321 llvm::APInt &Result) {
5322 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5323 "Can't get the size of a non alloc_size function");
5324 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5325 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5326 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5327}
5328
5329/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5330/// a function with the alloc_size attribute. If it was possible to do so, this
5331/// function will return true, make Result's Base point to said function call,
5332/// and mark Result's Base as invalid.
5333static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5334 LValue &Result) {
5335 if (!Info.allowInvalidBaseExpr() || Base.isNull())
5336 return false;
5337
5338 // Because we do no form of static analysis, we only support const variables.
5339 //
5340 // Additionally, we can't support parameters, nor can we support static
5341 // variables (in the latter case, use-before-assign isn't UB; in the former,
5342 // we have no clue what they'll be assigned to).
5343 const auto *VD =
5344 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5345 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5346 return false;
5347
5348 const Expr *Init = VD->getAnyInitializer();
5349 if (!Init)
5350 return false;
5351
5352 const Expr *E = Init->IgnoreParens();
5353 if (!tryUnwrapAllocSizeCall(E))
5354 return false;
5355
5356 // Store E instead of E unwrapped so that the type of the LValue's base is
5357 // what the user wanted.
5358 Result.setInvalid(E);
5359
5360 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5361 Result.addUnsizedArray(Info, Pointee);
5362 return true;
5363}
5364
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005365namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005366class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005367 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005368 LValue &Result;
5369
Peter Collingbournee9200682011-05-13 03:29:01 +00005370 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005371 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005372 return true;
5373 }
George Burgess IVe3763372016-12-22 02:50:20 +00005374
5375 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005376public:
Mike Stump11289f42009-09-09 15:08:12 +00005377
John McCall45d55e42010-05-07 21:00:08 +00005378 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005379 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005380
Richard Smith2e312c82012-03-03 22:46:17 +00005381 bool Success(const APValue &V, const Expr *E) {
5382 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005383 return true;
5384 }
Richard Smithfddd3842011-12-30 21:15:51 +00005385 bool ZeroInitialization(const Expr *E) {
Yaxun Liu402804b2016-12-15 08:09:08 +00005386 auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
5387 Result.set((Expr*)nullptr, 0, false, true, Offset);
5388 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005389 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005390
John McCall45d55e42010-05-07 21:00:08 +00005391 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005392 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005393 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005394 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005395 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00005396 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005397 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005398 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005399 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005400 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005401 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005402 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005403 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005404 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005405 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005406 }
Richard Smithd62306a2011-11-10 06:34:14 +00005407 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005408 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005409 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005410 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005411 if (!Info.CurrentCall->This) {
5412 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005413 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005414 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005415 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005416 return false;
5417 }
Richard Smithd62306a2011-11-10 06:34:14 +00005418 Result = *Info.CurrentCall->This;
5419 return true;
5420 }
John McCallc07a0c72011-02-17 10:25:35 +00005421
Eli Friedman449fe542009-03-23 04:56:01 +00005422 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005423};
Chris Lattner05706e882008-07-11 18:11:29 +00005424} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005425
John McCall45d55e42010-05-07 21:00:08 +00005426static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005427 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00005428 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005429}
5430
John McCall45d55e42010-05-07 21:00:08 +00005431bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005432 if (E->getOpcode() != BO_Add &&
5433 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005434 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005435
Chris Lattner05706e882008-07-11 18:11:29 +00005436 const Expr *PExp = E->getLHS();
5437 const Expr *IExp = E->getRHS();
5438 if (IExp->getType()->isPointerType())
5439 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005440
Richard Smith253c2a32012-01-27 01:14:48 +00005441 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00005442 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005443 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005444
John McCall45d55e42010-05-07 21:00:08 +00005445 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005446 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005447 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005448
Richard Smith96e0c102011-11-04 02:25:55 +00005449 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005450 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005451
Ted Kremenek28831752012-08-23 20:46:57 +00005452 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005453 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005454}
Eli Friedman9a156e52008-11-12 09:44:48 +00005455
John McCall45d55e42010-05-07 21:00:08 +00005456bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5457 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005458}
Mike Stump11289f42009-09-09 15:08:12 +00005459
Peter Collingbournee9200682011-05-13 03:29:01 +00005460bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5461 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005462
Eli Friedman847a2bc2009-12-27 05:43:15 +00005463 switch (E->getCastKind()) {
5464 default:
5465 break;
5466
John McCalle3027922010-08-25 11:45:40 +00005467 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005468 case CK_CPointerToObjCPointerCast:
5469 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005470 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005471 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005472 if (!Visit(SubExpr))
5473 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005474 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5475 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5476 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005477 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005478 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005479 if (SubExpr->getType()->isVoidPointerType())
5480 CCEDiag(E, diag::note_constexpr_invalid_cast)
5481 << 3 << SubExpr->getType();
5482 else
5483 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5484 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005485 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5486 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005487 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005488
Anders Carlsson18275092010-10-31 20:41:46 +00005489 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005490 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00005491 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00005492 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005493 if (!Result.Base && Result.Offset.isZero())
5494 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005495
Richard Smithd62306a2011-11-10 06:34:14 +00005496 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005497 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005498 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5499 castAs<PointerType>()->getPointeeType(),
5500 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005501
Richard Smith027bf112011-11-17 22:56:20 +00005502 case CK_BaseToDerived:
5503 if (!Visit(E->getSubExpr()))
5504 return false;
5505 if (!Result.Base && Result.Offset.isZero())
5506 return true;
5507 return HandleBaseToDerivedCast(Info, E, Result);
5508
Richard Smith0b0a0b62011-10-29 20:57:55 +00005509 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005510 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005511 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005512
John McCalle3027922010-08-25 11:45:40 +00005513 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005514 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5515
Richard Smith2e312c82012-03-03 22:46:17 +00005516 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005517 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005518 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005519
John McCall45d55e42010-05-07 21:00:08 +00005520 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005521 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5522 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005523 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005524 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005525 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005526 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005527 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005528 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005529 return true;
5530 } else {
5531 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005532 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005533 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005534 }
5535 }
John McCalle3027922010-08-25 11:45:40 +00005536 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005537 if (SubExpr->isGLValue()) {
5538 if (!EvaluateLValue(SubExpr, Result, Info))
5539 return false;
5540 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005541 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005542 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005543 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005544 return false;
5545 }
Richard Smith96e0c102011-11-04 02:25:55 +00005546 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005547 if (const ConstantArrayType *CAT
5548 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5549 Result.addArray(Info, E, CAT);
5550 else
5551 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005552 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005553
John McCalle3027922010-08-25 11:45:40 +00005554 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005555 return EvaluateLValue(SubExpr, Result, Info);
George Burgess IVe3763372016-12-22 02:50:20 +00005556
5557 case CK_LValueToRValue: {
5558 LValue LVal;
5559 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5560 return false;
5561
5562 APValue RVal;
5563 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5564 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5565 LVal, RVal))
5566 return evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5567 return Success(RVal, E);
5568 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005569 }
5570
Richard Smith11562c52011-10-28 17:51:58 +00005571 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005572}
Chris Lattner05706e882008-07-11 18:11:29 +00005573
Hal Finkel0dd05d42014-10-03 17:18:37 +00005574static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5575 // C++ [expr.alignof]p3:
5576 // When alignof is applied to a reference type, the result is the
5577 // alignment of the referenced type.
5578 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5579 T = Ref->getPointeeType();
5580
5581 // __alignof is defined to return the preferred alignment.
5582 return Info.Ctx.toCharUnitsFromBits(
5583 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5584}
5585
5586static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5587 E = E->IgnoreParens();
5588
5589 // The kinds of expressions that we have special-case logic here for
5590 // should be kept up to date with the special checks for those
5591 // expressions in Sema.
5592
5593 // alignof decl is always accepted, even if it doesn't make sense: we default
5594 // to 1 in those cases.
5595 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5596 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5597 /*RefAsPointee*/true);
5598
5599 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5600 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5601 /*RefAsPointee*/true);
5602
5603 return GetAlignOfType(Info, E->getType());
5604}
5605
George Burgess IVe3763372016-12-22 02:50:20 +00005606// To be clear: this happily visits unsupported builtins. Better name welcomed.
5607bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5608 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5609 return true;
5610
5611 if (!(Info.allowInvalidBaseExpr() && getAllocSizeAttr(E)))
5612 return false;
5613
5614 Result.setInvalid(E);
5615 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5616 Result.addUnsizedArray(Info, PointeeTy);
5617 return true;
5618}
5619
Peter Collingbournee9200682011-05-13 03:29:01 +00005620bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005621 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005622 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005623
Richard Smith6328cbd2016-11-16 00:57:23 +00005624 if (unsigned BuiltinOp = E->getBuiltinCallee())
5625 return VisitBuiltinCallExpr(E, BuiltinOp);
5626
George Burgess IVe3763372016-12-22 02:50:20 +00005627 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005628}
5629
5630bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5631 unsigned BuiltinOp) {
5632 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005633 case Builtin::BI__builtin_addressof:
5634 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005635 case Builtin::BI__builtin_assume_aligned: {
5636 // We need to be very careful here because: if the pointer does not have the
5637 // asserted alignment, then the behavior is undefined, and undefined
5638 // behavior is non-constant.
5639 if (!EvaluatePointer(E->getArg(0), Result, Info))
5640 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005641
Hal Finkel0dd05d42014-10-03 17:18:37 +00005642 LValue OffsetResult(Result);
5643 APSInt Alignment;
5644 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5645 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005646 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005647
5648 if (E->getNumArgs() > 2) {
5649 APSInt Offset;
5650 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5651 return false;
5652
Richard Smith642a2362017-01-30 23:30:26 +00005653 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005654 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5655 }
5656
5657 // If there is a base object, then it must have the correct alignment.
5658 if (OffsetResult.Base) {
5659 CharUnits BaseAlignment;
5660 if (const ValueDecl *VD =
5661 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5662 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5663 } else {
5664 BaseAlignment =
5665 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5666 }
5667
5668 if (BaseAlignment < Align) {
5669 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005670 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005671 CCEDiag(E->getArg(0),
5672 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005673 << (unsigned)BaseAlignment.getQuantity()
5674 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005675 return false;
5676 }
5677 }
5678
5679 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005680 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005681 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005682
Richard Smith642a2362017-01-30 23:30:26 +00005683 (OffsetResult.Base
5684 ? CCEDiag(E->getArg(0),
5685 diag::note_constexpr_baa_insufficient_alignment) << 1
5686 : CCEDiag(E->getArg(0),
5687 diag::note_constexpr_baa_value_insufficient_alignment))
5688 << (int)OffsetResult.Offset.getQuantity()
5689 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005690 return false;
5691 }
5692
5693 return true;
5694 }
Richard Smithe9507952016-11-12 01:39:56 +00005695
5696 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005697 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005698 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005699 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005700 if (Info.getLangOpts().CPlusPlus11)
5701 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5702 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005703 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005704 else
5705 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5706 // Fall through.
5707 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005708 case Builtin::BI__builtin_wcschr:
5709 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005710 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005711 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005712 if (!Visit(E->getArg(0)))
5713 return false;
5714 APSInt Desired;
5715 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5716 return false;
5717 uint64_t MaxLength = uint64_t(-1);
5718 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005719 BuiltinOp != Builtin::BIwcschr &&
5720 BuiltinOp != Builtin::BI__builtin_strchr &&
5721 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005722 APSInt N;
5723 if (!EvaluateInteger(E->getArg(2), N, Info))
5724 return false;
5725 MaxLength = N.getExtValue();
5726 }
5727
Richard Smith8110c9d2016-11-29 19:45:17 +00005728 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005729
Richard Smith8110c9d2016-11-29 19:45:17 +00005730 // Figure out what value we're actually looking for (after converting to
5731 // the corresponding unsigned type if necessary).
5732 uint64_t DesiredVal;
5733 bool StopAtNull = false;
5734 switch (BuiltinOp) {
5735 case Builtin::BIstrchr:
5736 case Builtin::BI__builtin_strchr:
5737 // strchr compares directly to the passed integer, and therefore
5738 // always fails if given an int that is not a char.
5739 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5740 E->getArg(1)->getType(),
5741 Desired),
5742 Desired))
5743 return ZeroInitialization(E);
5744 StopAtNull = true;
5745 // Fall through.
5746 case Builtin::BImemchr:
5747 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005748 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005749 // memchr compares by converting both sides to unsigned char. That's also
5750 // correct for strchr if we get this far (to cope with plain char being
5751 // unsigned in the strchr case).
5752 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5753 break;
Richard Smithe9507952016-11-12 01:39:56 +00005754
Richard Smith8110c9d2016-11-29 19:45:17 +00005755 case Builtin::BIwcschr:
5756 case Builtin::BI__builtin_wcschr:
5757 StopAtNull = true;
5758 // Fall through.
5759 case Builtin::BIwmemchr:
5760 case Builtin::BI__builtin_wmemchr:
5761 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5762 DesiredVal = Desired.getZExtValue();
5763 break;
5764 }
Richard Smithe9507952016-11-12 01:39:56 +00005765
5766 for (; MaxLength; --MaxLength) {
5767 APValue Char;
5768 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5769 !Char.isInt())
5770 return false;
5771 if (Char.getInt().getZExtValue() == DesiredVal)
5772 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005773 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005774 break;
5775 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5776 return false;
5777 }
5778 // Not found: return nullptr.
5779 return ZeroInitialization(E);
5780 }
5781
Richard Smith6cbd65d2013-07-11 02:27:57 +00005782 default:
George Burgess IVe3763372016-12-22 02:50:20 +00005783 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005784 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005785}
Chris Lattner05706e882008-07-11 18:11:29 +00005786
5787//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005788// Member Pointer Evaluation
5789//===----------------------------------------------------------------------===//
5790
5791namespace {
5792class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005793 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005794 MemberPtr &Result;
5795
5796 bool Success(const ValueDecl *D) {
5797 Result = MemberPtr(D);
5798 return true;
5799 }
5800public:
5801
5802 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5803 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5804
Richard Smith2e312c82012-03-03 22:46:17 +00005805 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005806 Result.setFrom(V);
5807 return true;
5808 }
Richard Smithfddd3842011-12-30 21:15:51 +00005809 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005810 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005811 }
5812
5813 bool VisitCastExpr(const CastExpr *E);
5814 bool VisitUnaryAddrOf(const UnaryOperator *E);
5815};
5816} // end anonymous namespace
5817
5818static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5819 EvalInfo &Info) {
5820 assert(E->isRValue() && E->getType()->isMemberPointerType());
5821 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5822}
5823
5824bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5825 switch (E->getCastKind()) {
5826 default:
5827 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5828
5829 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005830 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005831 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005832
5833 case CK_BaseToDerivedMemberPointer: {
5834 if (!Visit(E->getSubExpr()))
5835 return false;
5836 if (E->path_empty())
5837 return true;
5838 // Base-to-derived member pointer casts store the path in derived-to-base
5839 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5840 // the wrong end of the derived->base arc, so stagger the path by one class.
5841 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5842 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5843 PathI != PathE; ++PathI) {
5844 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5845 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5846 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005847 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005848 }
5849 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5850 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005851 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005852 return true;
5853 }
5854
5855 case CK_DerivedToBaseMemberPointer:
5856 if (!Visit(E->getSubExpr()))
5857 return false;
5858 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5859 PathE = E->path_end(); PathI != PathE; ++PathI) {
5860 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5861 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5862 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005863 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005864 }
5865 return true;
5866 }
5867}
5868
5869bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5870 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5871 // member can be formed.
5872 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5873}
5874
5875//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005876// Record Evaluation
5877//===----------------------------------------------------------------------===//
5878
5879namespace {
5880 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005881 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005882 const LValue &This;
5883 APValue &Result;
5884 public:
5885
5886 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5887 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5888
Richard Smith2e312c82012-03-03 22:46:17 +00005889 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005890 Result = V;
5891 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005892 }
Richard Smithb8348f52016-05-12 22:16:28 +00005893 bool ZeroInitialization(const Expr *E) {
5894 return ZeroInitialization(E, E->getType());
5895 }
5896 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005897
Richard Smith52a980a2015-08-28 02:43:42 +00005898 bool VisitCallExpr(const CallExpr *E) {
5899 return handleCallExpr(E, Result, &This);
5900 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005901 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005902 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005903 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5904 return VisitCXXConstructExpr(E, E->getType());
5905 }
Faisal Valic72a08c2017-01-09 03:02:53 +00005906 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00005907 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005908 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005909 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005910 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005911}
Richard Smithd62306a2011-11-10 06:34:14 +00005912
Richard Smithfddd3842011-12-30 21:15:51 +00005913/// Perform zero-initialization on an object of non-union class type.
5914/// C++11 [dcl.init]p5:
5915/// To zero-initialize an object or reference of type T means:
5916/// [...]
5917/// -- if T is a (possibly cv-qualified) non-union class type,
5918/// each non-static data member and each base-class subobject is
5919/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005920static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5921 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005922 const LValue &This, APValue &Result) {
5923 assert(!RD->isUnion() && "Expected non-union class type");
5924 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5925 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005926 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005927
John McCalld7bca762012-05-01 00:38:49 +00005928 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005929 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5930
5931 if (CD) {
5932 unsigned Index = 0;
5933 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005934 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005935 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5936 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005937 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5938 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005939 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005940 Result.getStructBase(Index)))
5941 return false;
5942 }
5943 }
5944
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005945 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005946 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005947 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005948 continue;
5949
5950 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005951 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005952 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005953
David Blaikie2d7c57e2012-04-30 02:36:29 +00005954 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005955 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005956 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005957 return false;
5958 }
5959
5960 return true;
5961}
5962
Richard Smithb8348f52016-05-12 22:16:28 +00005963bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5964 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005965 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005966 if (RD->isUnion()) {
5967 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5968 // object's first non-static named data member is zero-initialized
5969 RecordDecl::field_iterator I = RD->field_begin();
5970 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005971 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005972 return true;
5973 }
5974
5975 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005976 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005977 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005978 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005979 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005980 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005981 }
5982
Richard Smith5d108602012-02-17 00:44:16 +00005983 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005984 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005985 return false;
5986 }
5987
Richard Smitha8105bc2012-01-06 16:39:00 +00005988 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005989}
5990
Richard Smithe97cbd72011-11-11 04:05:33 +00005991bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5992 switch (E->getCastKind()) {
5993 default:
5994 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5995
5996 case CK_ConstructorConversion:
5997 return Visit(E->getSubExpr());
5998
5999 case CK_DerivedToBase:
6000 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006001 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006002 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006003 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006004 if (!DerivedObject.isStruct())
6005 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006006
6007 // Derived-to-base rvalue conversion: just slice off the derived part.
6008 APValue *Value = &DerivedObject;
6009 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6010 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6011 PathE = E->path_end(); PathI != PathE; ++PathI) {
6012 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6013 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6014 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6015 RD = Base;
6016 }
6017 Result = *Value;
6018 return true;
6019 }
6020 }
6021}
6022
Richard Smithd62306a2011-11-10 06:34:14 +00006023bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006024 if (E->isTransparent())
6025 return Visit(E->getInit(0));
6026
Richard Smithd62306a2011-11-10 06:34:14 +00006027 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006028 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006029 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6030
6031 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006032 const FieldDecl *Field = E->getInitializedFieldInUnion();
6033 Result = APValue(Field);
6034 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006035 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006036
6037 // If the initializer list for a union does not contain any elements, the
6038 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006039 // FIXME: The element should be initialized from an initializer list.
6040 // Is this difference ever observable for initializer lists which
6041 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006042 ImplicitValueInitExpr VIE(Field->getType());
6043 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6044
Richard Smithd62306a2011-11-10 06:34:14 +00006045 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006046 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6047 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006048
6049 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6050 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6051 isa<CXXDefaultInitExpr>(InitExpr));
6052
Richard Smithb228a862012-02-15 02:18:13 +00006053 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006054 }
6055
Richard Smith872307e2016-03-08 22:17:41 +00006056 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006057 if (Result.isUninit())
6058 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6059 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006060 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006061 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006062
6063 // Initialize base classes.
6064 if (CXXRD) {
6065 for (const auto &Base : CXXRD->bases()) {
6066 assert(ElementNo < E->getNumInits() && "missing init for base class");
6067 const Expr *Init = E->getInit(ElementNo);
6068
6069 LValue Subobject = This;
6070 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6071 return false;
6072
6073 APValue &FieldVal = Result.getStructBase(ElementNo);
6074 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006075 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006076 return false;
6077 Success = false;
6078 }
6079 ++ElementNo;
6080 }
6081 }
6082
6083 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006084 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006085 // Anonymous bit-fields are not considered members of the class for
6086 // purposes of aggregate initialization.
6087 if (Field->isUnnamedBitfield())
6088 continue;
6089
6090 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006091
Richard Smith253c2a32012-01-27 01:14:48 +00006092 bool HaveInit = ElementNo < E->getNumInits();
6093
6094 // FIXME: Diagnostics here should point to the end of the initializer
6095 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006096 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006097 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006098 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006099
6100 // Perform an implicit value-initialization for members beyond the end of
6101 // the initializer list.
6102 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006103 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006104
Richard Smith852c9db2013-04-20 22:23:05 +00006105 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6106 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6107 isa<CXXDefaultInitExpr>(Init));
6108
Richard Smith49ca8aa2013-08-06 07:09:20 +00006109 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6110 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6111 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006112 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006113 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006114 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006115 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006116 }
6117 }
6118
Richard Smith253c2a32012-01-27 01:14:48 +00006119 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006120}
6121
Richard Smithb8348f52016-05-12 22:16:28 +00006122bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6123 QualType T) {
6124 // Note that E's type is not necessarily the type of our class here; we might
6125 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006126 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006127 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6128
Richard Smithfddd3842011-12-30 21:15:51 +00006129 bool ZeroInit = E->requiresZeroInitialization();
6130 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006131 // If we've already performed zero-initialization, we're already done.
6132 if (!Result.isUninit())
6133 return true;
6134
Richard Smithda3f4fd2014-03-05 23:32:50 +00006135 // We can get here in two different ways:
6136 // 1) We're performing value-initialization, and should zero-initialize
6137 // the object, or
6138 // 2) We're performing default-initialization of an object with a trivial
6139 // constexpr default constructor, in which case we should start the
6140 // lifetimes of all the base subobjects (there can be no data member
6141 // subobjects in this case) per [basic.life]p1.
6142 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006143 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006144 }
6145
Craig Topper36250ad2014-05-12 05:36:57 +00006146 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006147 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006148
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006149 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006150 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006151
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006152 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006153 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006154 if (const MaterializeTemporaryExpr *ME
6155 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6156 return Visit(ME->GetTemporaryExpr());
6157
Richard Smithb8348f52016-05-12 22:16:28 +00006158 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006159 return false;
6160
Craig Topper5fc8fc22014-08-27 06:28:36 +00006161 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006162 return HandleConstructorCall(E, This, Args,
6163 cast<CXXConstructorDecl>(Definition), Info,
6164 Result);
6165}
6166
6167bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6168 const CXXInheritedCtorInitExpr *E) {
6169 if (!Info.CurrentCall) {
6170 assert(Info.checkingPotentialConstantExpression());
6171 return false;
6172 }
6173
6174 const CXXConstructorDecl *FD = E->getConstructor();
6175 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6176 return false;
6177
6178 const FunctionDecl *Definition = nullptr;
6179 auto Body = FD->getBody(Definition);
6180
6181 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6182 return false;
6183
6184 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006185 cast<CXXConstructorDecl>(Definition), Info,
6186 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006187}
6188
Richard Smithcc1b96d2013-06-12 22:31:48 +00006189bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6190 const CXXStdInitializerListExpr *E) {
6191 const ConstantArrayType *ArrayType =
6192 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6193
6194 LValue Array;
6195 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6196 return false;
6197
6198 // Get a pointer to the first element of the array.
6199 Array.addArray(Info, E, ArrayType);
6200
6201 // FIXME: Perform the checks on the field types in SemaInit.
6202 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6203 RecordDecl::field_iterator Field = Record->field_begin();
6204 if (Field == Record->field_end())
6205 return Error(E);
6206
6207 // Start pointer.
6208 if (!Field->getType()->isPointerType() ||
6209 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6210 ArrayType->getElementType()))
6211 return Error(E);
6212
6213 // FIXME: What if the initializer_list type has base classes, etc?
6214 Result = APValue(APValue::UninitStruct(), 0, 2);
6215 Array.moveInto(Result.getStructField(0));
6216
6217 if (++Field == Record->field_end())
6218 return Error(E);
6219
6220 if (Field->getType()->isPointerType() &&
6221 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6222 ArrayType->getElementType())) {
6223 // End pointer.
6224 if (!HandleLValueArrayAdjustment(Info, E, Array,
6225 ArrayType->getElementType(),
6226 ArrayType->getSize().getZExtValue()))
6227 return false;
6228 Array.moveInto(Result.getStructField(1));
6229 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6230 // Length.
6231 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6232 else
6233 return Error(E);
6234
6235 if (++Field != Record->field_end())
6236 return Error(E);
6237
6238 return true;
6239}
6240
Faisal Valic72a08c2017-01-09 03:02:53 +00006241bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6242 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6243 if (ClosureClass->isInvalidDecl()) return false;
6244
6245 if (Info.checkingPotentialConstantExpression()) return true;
6246 if (E->capture_size()) {
6247 Info.FFDiag(E, diag::note_unimplemented_constexpr_lambda_feature_ast)
6248 << "can not evaluate lambda expressions with captures";
6249 return false;
6250 }
6251 // FIXME: Implement captures.
6252 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, /*NumFields*/0);
6253 return true;
6254}
6255
Richard Smithd62306a2011-11-10 06:34:14 +00006256static bool EvaluateRecord(const Expr *E, const LValue &This,
6257 APValue &Result, EvalInfo &Info) {
6258 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006259 "can't evaluate expression as a record rvalue");
6260 return RecordExprEvaluator(Info, This, Result).Visit(E);
6261}
6262
6263//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006264// Temporary Evaluation
6265//
6266// Temporaries are represented in the AST as rvalues, but generally behave like
6267// lvalues. The full-object of which the temporary is a subobject is implicitly
6268// materialized so that a reference can bind to it.
6269//===----------------------------------------------------------------------===//
6270namespace {
6271class TemporaryExprEvaluator
6272 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6273public:
6274 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6275 LValueExprEvaluatorBaseTy(Info, Result) {}
6276
6277 /// Visit an expression which constructs the value of this temporary.
6278 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006279 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006280 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6281 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006282 }
6283
6284 bool VisitCastExpr(const CastExpr *E) {
6285 switch (E->getCastKind()) {
6286 default:
6287 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6288
6289 case CK_ConstructorConversion:
6290 return VisitConstructExpr(E->getSubExpr());
6291 }
6292 }
6293 bool VisitInitListExpr(const InitListExpr *E) {
6294 return VisitConstructExpr(E);
6295 }
6296 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6297 return VisitConstructExpr(E);
6298 }
6299 bool VisitCallExpr(const CallExpr *E) {
6300 return VisitConstructExpr(E);
6301 }
Richard Smith513955c2014-12-17 19:24:30 +00006302 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6303 return VisitConstructExpr(E);
6304 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006305 bool VisitLambdaExpr(const LambdaExpr *E) {
6306 return VisitConstructExpr(E);
6307 }
Richard Smith027bf112011-11-17 22:56:20 +00006308};
6309} // end anonymous namespace
6310
6311/// Evaluate an expression of record type as a temporary.
6312static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006313 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006314 return TemporaryExprEvaluator(Info, Result).Visit(E);
6315}
6316
6317//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006318// Vector Evaluation
6319//===----------------------------------------------------------------------===//
6320
6321namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006322 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006323 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006324 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006325 public:
Mike Stump11289f42009-09-09 15:08:12 +00006326
Richard Smith2d406342011-10-22 21:10:00 +00006327 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6328 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006329
Craig Topper9798b932015-09-29 04:30:05 +00006330 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006331 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6332 // FIXME: remove this APValue copy.
6333 Result = APValue(V.data(), V.size());
6334 return true;
6335 }
Richard Smith2e312c82012-03-03 22:46:17 +00006336 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006337 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006338 Result = V;
6339 return true;
6340 }
Richard Smithfddd3842011-12-30 21:15:51 +00006341 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006342
Richard Smith2d406342011-10-22 21:10:00 +00006343 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006344 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006345 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006346 bool VisitInitListExpr(const InitListExpr *E);
6347 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006348 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006349 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006350 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006351 };
6352} // end anonymous namespace
6353
6354static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006355 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006356 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006357}
6358
George Burgess IV533ff002015-12-11 00:23:35 +00006359bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006360 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006361 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006362
Richard Smith161f09a2011-12-06 22:44:34 +00006363 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006364 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006365
Eli Friedmanc757de22011-03-25 00:43:55 +00006366 switch (E->getCastKind()) {
6367 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006368 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006369 if (SETy->isIntegerType()) {
6370 APSInt IntResult;
6371 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006372 return false;
6373 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006374 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006375 APFloat FloatResult(0.0);
6376 if (!EvaluateFloat(SE, FloatResult, Info))
6377 return false;
6378 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006379 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006380 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006381 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006382
6383 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006384 SmallVector<APValue, 4> Elts(NElts, Val);
6385 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006386 }
Eli Friedman803acb32011-12-22 03:51:45 +00006387 case CK_BitCast: {
6388 // Evaluate the operand into an APInt we can extract from.
6389 llvm::APInt SValInt;
6390 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6391 return false;
6392 // Extract the elements
6393 QualType EltTy = VTy->getElementType();
6394 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6395 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6396 SmallVector<APValue, 4> Elts;
6397 if (EltTy->isRealFloatingType()) {
6398 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006399 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006400 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006401 FloatEltSize = 80;
6402 for (unsigned i = 0; i < NElts; i++) {
6403 llvm::APInt Elt;
6404 if (BigEndian)
6405 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6406 else
6407 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006408 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006409 }
6410 } else if (EltTy->isIntegerType()) {
6411 for (unsigned i = 0; i < NElts; i++) {
6412 llvm::APInt Elt;
6413 if (BigEndian)
6414 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6415 else
6416 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6417 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6418 }
6419 } else {
6420 return Error(E);
6421 }
6422 return Success(Elts, E);
6423 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006424 default:
Richard Smith11562c52011-10-28 17:51:58 +00006425 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006426 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006427}
6428
Richard Smith2d406342011-10-22 21:10:00 +00006429bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006430VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006431 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006432 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006433 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006434
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006435 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006436 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006437
Eli Friedmanb9c71292012-01-03 23:24:20 +00006438 // The number of initializers can be less than the number of
6439 // vector elements. For OpenCL, this can be due to nested vector
6440 // initialization. For GCC compatibility, missing trailing elements
6441 // should be initialized with zeroes.
6442 unsigned CountInits = 0, CountElts = 0;
6443 while (CountElts < NumElements) {
6444 // Handle nested vector initialization.
6445 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006446 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006447 APValue v;
6448 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6449 return Error(E);
6450 unsigned vlen = v.getVectorLength();
6451 for (unsigned j = 0; j < vlen; j++)
6452 Elements.push_back(v.getVectorElt(j));
6453 CountElts += vlen;
6454 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006455 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006456 if (CountInits < NumInits) {
6457 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006458 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006459 } else // trailing integer zero.
6460 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6461 Elements.push_back(APValue(sInt));
6462 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006463 } else {
6464 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006465 if (CountInits < NumInits) {
6466 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006467 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006468 } else // trailing float zero.
6469 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6470 Elements.push_back(APValue(f));
6471 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006472 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006473 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006474 }
Richard Smith2d406342011-10-22 21:10:00 +00006475 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006476}
6477
Richard Smith2d406342011-10-22 21:10:00 +00006478bool
Richard Smithfddd3842011-12-30 21:15:51 +00006479VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006480 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006481 QualType EltTy = VT->getElementType();
6482 APValue ZeroElement;
6483 if (EltTy->isIntegerType())
6484 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6485 else
6486 ZeroElement =
6487 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6488
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006489 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006490 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006491}
6492
Richard Smith2d406342011-10-22 21:10:00 +00006493bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006494 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006495 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006496}
6497
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006498//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006499// Array Evaluation
6500//===----------------------------------------------------------------------===//
6501
6502namespace {
6503 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006504 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006505 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006506 APValue &Result;
6507 public:
6508
Richard Smithd62306a2011-11-10 06:34:14 +00006509 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6510 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006511
6512 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006513 assert((V.isArray() || V.isLValue()) &&
6514 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006515 Result = V;
6516 return true;
6517 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006518
Richard Smithfddd3842011-12-30 21:15:51 +00006519 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006520 const ConstantArrayType *CAT =
6521 Info.Ctx.getAsConstantArrayType(E->getType());
6522 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006523 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006524
6525 Result = APValue(APValue::UninitArray(), 0,
6526 CAT->getSize().getZExtValue());
6527 if (!Result.hasArrayFiller()) return true;
6528
Richard Smithfddd3842011-12-30 21:15:51 +00006529 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006530 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006531 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006532 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006533 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006534 }
6535
Richard Smith52a980a2015-08-28 02:43:42 +00006536 bool VisitCallExpr(const CallExpr *E) {
6537 return handleCallExpr(E, Result, &This);
6538 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006539 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006540 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006541 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006542 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6543 const LValue &Subobject,
6544 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006545 };
6546} // end anonymous namespace
6547
Richard Smithd62306a2011-11-10 06:34:14 +00006548static bool EvaluateArray(const Expr *E, const LValue &This,
6549 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006550 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006551 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006552}
6553
6554bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6555 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6556 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006557 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006558
Richard Smithca2cfbf2011-12-22 01:07:19 +00006559 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6560 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006561 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006562 LValue LV;
6563 if (!EvaluateLValue(E->getInit(0), LV, Info))
6564 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006565 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006566 LV.moveInto(Val);
6567 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006568 }
6569
Richard Smith253c2a32012-01-27 01:14:48 +00006570 bool Success = true;
6571
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006572 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6573 "zero-initialized array shouldn't have any initialized elts");
6574 APValue Filler;
6575 if (Result.isArray() && Result.hasArrayFiller())
6576 Filler = Result.getArrayFiller();
6577
Richard Smith9543c5e2013-04-22 14:44:29 +00006578 unsigned NumEltsToInit = E->getNumInits();
6579 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006580 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006581
6582 // If the initializer might depend on the array index, run it for each
6583 // array element. For now, just whitelist non-class value-initialization.
6584 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6585 NumEltsToInit = NumElts;
6586
6587 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006588
6589 // If the array was previously zero-initialized, preserve the
6590 // zero-initialized values.
6591 if (!Filler.isUninit()) {
6592 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6593 Result.getArrayInitializedElt(I) = Filler;
6594 if (Result.hasArrayFiller())
6595 Result.getArrayFiller() = Filler;
6596 }
6597
Richard Smithd62306a2011-11-10 06:34:14 +00006598 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006599 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006600 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6601 const Expr *Init =
6602 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006603 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006604 Info, Subobject, Init) ||
6605 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006606 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006607 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006608 return false;
6609 Success = false;
6610 }
Richard Smithd62306a2011-11-10 06:34:14 +00006611 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006612
Richard Smith9543c5e2013-04-22 14:44:29 +00006613 if (!Result.hasArrayFiller())
6614 return Success;
6615
6616 // If we get here, we have a trivial filler, which we can just evaluate
6617 // once and splat over the rest of the array elements.
6618 assert(FillerExpr && "no array filler for incomplete init list");
6619 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6620 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006621}
6622
Richard Smith410306b2016-12-12 02:53:20 +00006623bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6624 if (E->getCommonExpr() &&
6625 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6626 Info, E->getCommonExpr()->getSourceExpr()))
6627 return false;
6628
6629 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6630
6631 uint64_t Elements = CAT->getSize().getZExtValue();
6632 Result = APValue(APValue::UninitArray(), Elements, Elements);
6633
6634 LValue Subobject = This;
6635 Subobject.addArray(Info, E, CAT);
6636
6637 bool Success = true;
6638 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6639 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6640 Info, Subobject, E->getSubExpr()) ||
6641 !HandleLValueArrayAdjustment(Info, E, Subobject,
6642 CAT->getElementType(), 1)) {
6643 if (!Info.noteFailure())
6644 return false;
6645 Success = false;
6646 }
6647 }
6648
6649 return Success;
6650}
6651
Richard Smith027bf112011-11-17 22:56:20 +00006652bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006653 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6654}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006655
Richard Smith9543c5e2013-04-22 14:44:29 +00006656bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6657 const LValue &Subobject,
6658 APValue *Value,
6659 QualType Type) {
6660 bool HadZeroInit = !Value->isUninit();
6661
6662 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6663 unsigned N = CAT->getSize().getZExtValue();
6664
6665 // Preserve the array filler if we had prior zero-initialization.
6666 APValue Filler =
6667 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6668 : APValue();
6669
6670 *Value = APValue(APValue::UninitArray(), N, N);
6671
6672 if (HadZeroInit)
6673 for (unsigned I = 0; I != N; ++I)
6674 Value->getArrayInitializedElt(I) = Filler;
6675
6676 // Initialize the elements.
6677 LValue ArrayElt = Subobject;
6678 ArrayElt.addArray(Info, E, CAT);
6679 for (unsigned I = 0; I != N; ++I)
6680 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6681 CAT->getElementType()) ||
6682 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6683 CAT->getElementType(), 1))
6684 return false;
6685
6686 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006687 }
Richard Smith027bf112011-11-17 22:56:20 +00006688
Richard Smith9543c5e2013-04-22 14:44:29 +00006689 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006690 return Error(E);
6691
Richard Smithb8348f52016-05-12 22:16:28 +00006692 return RecordExprEvaluator(Info, Subobject, *Value)
6693 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006694}
6695
Richard Smithf3e9e432011-11-07 09:22:26 +00006696//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006697// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006698//
6699// As a GNU extension, we support casting pointers to sufficiently-wide integer
6700// types and back in constant folding. Integer values are thus represented
6701// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006702//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006703
6704namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006705class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006706 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006707 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006708public:
Richard Smith2e312c82012-03-03 22:46:17 +00006709 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006710 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006711
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006712 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006713 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006714 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006715 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006716 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006717 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006718 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006719 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006720 return true;
6721 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006722 bool Success(const llvm::APSInt &SI, const Expr *E) {
6723 return Success(SI, E, Result);
6724 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006725
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006726 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006727 assert(E->getType()->isIntegralOrEnumerationType() &&
6728 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006729 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006730 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006731 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006732 Result.getInt().setIsUnsigned(
6733 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006734 return true;
6735 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006736 bool Success(const llvm::APInt &I, const Expr *E) {
6737 return Success(I, E, Result);
6738 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006739
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006740 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006741 assert(E->getType()->isIntegralOrEnumerationType() &&
6742 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006743 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006744 return true;
6745 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006746 bool Success(uint64_t Value, const Expr *E) {
6747 return Success(Value, E, Result);
6748 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006749
Ken Dyckdbc01912011-03-11 02:13:43 +00006750 bool Success(CharUnits Size, const Expr *E) {
6751 return Success(Size.getQuantity(), E);
6752 }
6753
Richard Smith2e312c82012-03-03 22:46:17 +00006754 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006755 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006756 Result = V;
6757 return true;
6758 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006759 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006760 }
Mike Stump11289f42009-09-09 15:08:12 +00006761
Richard Smithfddd3842011-12-30 21:15:51 +00006762 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006763
Peter Collingbournee9200682011-05-13 03:29:01 +00006764 //===--------------------------------------------------------------------===//
6765 // Visitor Methods
6766 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006767
Chris Lattner7174bf32008-07-12 00:38:25 +00006768 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006769 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006770 }
6771 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006772 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006773 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006774
6775 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6776 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006777 if (CheckReferencedDecl(E, E->getDecl()))
6778 return true;
6779
6780 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006781 }
6782 bool VisitMemberExpr(const MemberExpr *E) {
6783 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006784 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006785 return true;
6786 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006787
6788 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006789 }
6790
Peter Collingbournee9200682011-05-13 03:29:01 +00006791 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006792 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006793 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006794 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006795 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006796
Peter Collingbournee9200682011-05-13 03:29:01 +00006797 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006798 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006799
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006800 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006801 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006802 }
Mike Stump11289f42009-09-09 15:08:12 +00006803
Ted Kremeneke65b0862012-03-06 20:05:56 +00006804 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6805 return Success(E->getValue(), E);
6806 }
Richard Smith410306b2016-12-12 02:53:20 +00006807
6808 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6809 if (Info.ArrayInitIndex == uint64_t(-1)) {
6810 // We were asked to evaluate this subexpression independent of the
6811 // enclosing ArrayInitLoopExpr. We can't do that.
6812 Info.FFDiag(E);
6813 return false;
6814 }
6815 return Success(Info.ArrayInitIndex, E);
6816 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00006817
Richard Smith4ce706a2011-10-11 21:43:33 +00006818 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006819 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006820 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006821 }
6822
Douglas Gregor29c42f22012-02-24 07:38:34 +00006823 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6824 return Success(E->getValue(), E);
6825 }
6826
John Wiegley6242b6a2011-04-28 00:16:57 +00006827 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6828 return Success(E->getValue(), E);
6829 }
6830
John Wiegleyf9f65842011-04-25 06:54:41 +00006831 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6832 return Success(E->getValue(), E);
6833 }
6834
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006835 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006836 bool VisitUnaryImag(const UnaryOperator *E);
6837
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006838 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006839 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006840
Eli Friedman4e7a2412009-02-27 04:45:43 +00006841 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006842};
Chris Lattner05706e882008-07-11 18:11:29 +00006843} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006844
Richard Smith11562c52011-10-28 17:51:58 +00006845/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6846/// produce either the integer value or a pointer.
6847///
6848/// GCC has a heinous extension which folds casts between pointer types and
6849/// pointer-sized integral types. We support this by allowing the evaluation of
6850/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6851/// Some simple arithmetic on such values is supported (they are treated much
6852/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006853static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006854 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006855 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006856 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006857}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006858
Richard Smithf57d8cb2011-12-09 22:58:01 +00006859static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006860 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006861 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006862 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006863 if (!Val.isInt()) {
6864 // FIXME: It would be better to produce the diagnostic for casting
6865 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00006866 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006867 return false;
6868 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006869 Result = Val.getInt();
6870 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006871}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006872
Richard Smithf57d8cb2011-12-09 22:58:01 +00006873/// Check whether the given declaration can be directly converted to an integral
6874/// rvalue. If not, no diagnostic is produced; there are other things we can
6875/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006876bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006877 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006878 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006879 // Check for signedness/width mismatches between E type and ECD value.
6880 bool SameSign = (ECD->getInitVal().isSigned()
6881 == E->getType()->isSignedIntegerOrEnumerationType());
6882 bool SameWidth = (ECD->getInitVal().getBitWidth()
6883 == Info.Ctx.getIntWidth(E->getType()));
6884 if (SameSign && SameWidth)
6885 return Success(ECD->getInitVal(), E);
6886 else {
6887 // Get rid of mismatch (otherwise Success assertions will fail)
6888 // by computing a new value matching the type of E.
6889 llvm::APSInt Val = ECD->getInitVal();
6890 if (!SameSign)
6891 Val.setIsSigned(!ECD->getInitVal().isSigned());
6892 if (!SameWidth)
6893 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6894 return Success(Val, E);
6895 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006896 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006897 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006898}
6899
Chris Lattner86ee2862008-10-06 06:40:35 +00006900/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6901/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006902static int EvaluateBuiltinClassifyType(const CallExpr *E,
6903 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006904 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006905 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006906 enum gcc_type_class {
6907 no_type_class = -1,
6908 void_type_class, integer_type_class, char_type_class,
6909 enumeral_type_class, boolean_type_class,
6910 pointer_type_class, reference_type_class, offset_type_class,
6911 real_type_class, complex_type_class,
6912 function_type_class, method_type_class,
6913 record_type_class, union_type_class,
6914 array_type_class, string_type_class,
6915 lang_type_class
6916 };
Mike Stump11289f42009-09-09 15:08:12 +00006917
6918 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006919 // ideal, however it is what gcc does.
6920 if (E->getNumArgs() == 0)
6921 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006922
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006923 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6924 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6925
6926 switch (CanTy->getTypeClass()) {
6927#define TYPE(ID, BASE)
6928#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6929#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6930#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6931#include "clang/AST/TypeNodes.def"
6932 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6933
6934 case Type::Builtin:
6935 switch (BT->getKind()) {
6936#define BUILTIN_TYPE(ID, SINGLETON_ID)
6937#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6938#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6939#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6940#include "clang/AST/BuiltinTypes.def"
6941 case BuiltinType::Void:
6942 return void_type_class;
6943
6944 case BuiltinType::Bool:
6945 return boolean_type_class;
6946
6947 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6948 case BuiltinType::UChar:
6949 case BuiltinType::UShort:
6950 case BuiltinType::UInt:
6951 case BuiltinType::ULong:
6952 case BuiltinType::ULongLong:
6953 case BuiltinType::UInt128:
6954 return integer_type_class;
6955
6956 case BuiltinType::NullPtr:
6957 return pointer_type_class;
6958
6959 case BuiltinType::WChar_U:
6960 case BuiltinType::Char16:
6961 case BuiltinType::Char32:
6962 case BuiltinType::ObjCId:
6963 case BuiltinType::ObjCClass:
6964 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00006965#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6966 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006967#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006968 case BuiltinType::OCLSampler:
6969 case BuiltinType::OCLEvent:
6970 case BuiltinType::OCLClkEvent:
6971 case BuiltinType::OCLQueue:
6972 case BuiltinType::OCLNDRange:
6973 case BuiltinType::OCLReserveID:
6974 case BuiltinType::Dependent:
6975 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6976 };
6977
6978 case Type::Enum:
6979 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6980 break;
6981
6982 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00006983 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006984 break;
6985
6986 case Type::MemberPointer:
6987 if (CanTy->isMemberDataPointerType())
6988 return offset_type_class;
6989 else {
6990 // We expect member pointers to be either data or function pointers,
6991 // nothing else.
6992 assert(CanTy->isMemberFunctionPointerType());
6993 return method_type_class;
6994 }
6995
6996 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00006997 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006998
6999 case Type::FunctionNoProto:
7000 case Type::FunctionProto:
7001 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7002
7003 case Type::Record:
7004 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7005 switch (RT->getDecl()->getTagKind()) {
7006 case TagTypeKind::TTK_Struct:
7007 case TagTypeKind::TTK_Class:
7008 case TagTypeKind::TTK_Interface:
7009 return record_type_class;
7010
7011 case TagTypeKind::TTK_Enum:
7012 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7013
7014 case TagTypeKind::TTK_Union:
7015 return union_type_class;
7016 }
7017 }
David Blaikie83d382b2011-09-23 05:06:16 +00007018 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007019
7020 case Type::ConstantArray:
7021 case Type::VariableArray:
7022 case Type::IncompleteArray:
7023 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7024
7025 case Type::BlockPointer:
7026 case Type::LValueReference:
7027 case Type::RValueReference:
7028 case Type::Vector:
7029 case Type::ExtVector:
7030 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007031 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007032 case Type::ObjCObject:
7033 case Type::ObjCInterface:
7034 case Type::ObjCObjectPointer:
7035 case Type::Pipe:
7036 case Type::Atomic:
7037 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7038 }
7039
7040 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007041}
7042
Richard Smith5fab0c92011-12-28 19:48:30 +00007043/// EvaluateBuiltinConstantPForLValue - Determine the result of
7044/// __builtin_constant_p when applied to the given lvalue.
7045///
7046/// An lvalue is only "constant" if it is a pointer or reference to the first
7047/// character of a string literal.
7048template<typename LValue>
7049static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007050 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007051 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7052}
7053
7054/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7055/// GCC as we can manage.
7056static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7057 QualType ArgType = Arg->getType();
7058
7059 // __builtin_constant_p always has one operand. The rules which gcc follows
7060 // are not precisely documented, but are as follows:
7061 //
7062 // - If the operand is of integral, floating, complex or enumeration type,
7063 // and can be folded to a known value of that type, it returns 1.
7064 // - If the operand and can be folded to a pointer to the first character
7065 // of a string literal (or such a pointer cast to an integral type), it
7066 // returns 1.
7067 //
7068 // Otherwise, it returns 0.
7069 //
7070 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7071 // its support for this does not currently work.
7072 if (ArgType->isIntegralOrEnumerationType()) {
7073 Expr::EvalResult Result;
7074 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7075 return false;
7076
7077 APValue &V = Result.Val;
7078 if (V.getKind() == APValue::Int)
7079 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007080 if (V.getKind() == APValue::LValue)
7081 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007082 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7083 return Arg->isEvaluatable(Ctx);
7084 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7085 LValue LV;
7086 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007087 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007088 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7089 : EvaluatePointer(Arg, LV, Info)) &&
7090 !Status.HasSideEffects)
7091 return EvaluateBuiltinConstantPForLValue(LV);
7092 }
7093
7094 // Anything else isn't considered to be sufficiently constant.
7095 return false;
7096}
7097
John McCall95007602010-05-10 23:27:23 +00007098/// Retrieves the "underlying object type" of the given expression,
7099/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007100static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007101 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7102 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007103 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007104 } else if (const Expr *E = B.get<const Expr*>()) {
7105 if (isa<CompoundLiteralExpr>(E))
7106 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007107 }
7108
7109 return QualType();
7110}
7111
George Burgess IV3a03fab2015-09-04 21:28:13 +00007112/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007113/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007114/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007115/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7116///
7117/// Always returns an RValue with a pointer representation.
7118static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7119 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7120
7121 auto *NoParens = E->IgnoreParens();
7122 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007123 if (Cast == nullptr)
7124 return NoParens;
7125
7126 // We only conservatively allow a few kinds of casts, because this code is
7127 // inherently a simple solution that seeks to support the common case.
7128 auto CastKind = Cast->getCastKind();
7129 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7130 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007131 return NoParens;
7132
7133 auto *SubExpr = Cast->getSubExpr();
7134 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7135 return NoParens;
7136 return ignorePointerCastsAndParens(SubExpr);
7137}
7138
George Burgess IVa51c4072015-10-16 01:49:01 +00007139/// Checks to see if the given LValue's Designator is at the end of the LValue's
7140/// record layout. e.g.
7141/// struct { struct { int a, b; } fst, snd; } obj;
7142/// obj.fst // no
7143/// obj.snd // yes
7144/// obj.fst.a // no
7145/// obj.fst.b // no
7146/// obj.snd.a // no
7147/// obj.snd.b // yes
7148///
7149/// Please note: this function is specialized for how __builtin_object_size
7150/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007151///
7152/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007153static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7154 assert(!LVal.Designator.Invalid);
7155
George Burgess IV4168d752016-06-27 19:40:41 +00007156 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7157 const RecordDecl *Parent = FD->getParent();
7158 Invalid = Parent->isInvalidDecl();
7159 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007160 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007161 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007162 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7163 };
7164
7165 auto &Base = LVal.getLValueBase();
7166 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7167 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007168 bool Invalid;
7169 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7170 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007171 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007172 for (auto *FD : IFD->chain()) {
7173 bool Invalid;
7174 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7175 return Invalid;
7176 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007177 }
7178 }
7179
George Burgess IVe3763372016-12-22 02:50:20 +00007180 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007181 QualType BaseType = getType(Base);
George Burgess IVe3763372016-12-22 02:50:20 +00007182 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7183 assert(isBaseAnAllocSizeCall(Base) &&
7184 "Unsized array in non-alloc_size call?");
7185 // If this is an alloc_size base, we should ignore the initial array index
7186 ++I;
7187 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7188 }
7189
7190 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7191 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007192 if (BaseType->isArrayType()) {
7193 // Because __builtin_object_size treats arrays as objects, we can ignore
7194 // the index iff this is the last array in the Designator.
7195 if (I + 1 == E)
7196 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007197 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7198 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007199 if (Index + 1 != CAT->getSize())
7200 return false;
7201 BaseType = CAT->getElementType();
7202 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007203 const auto *CT = BaseType->castAs<ComplexType>();
7204 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007205 if (Index != 1)
7206 return false;
7207 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007208 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007209 bool Invalid;
7210 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7211 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007212 BaseType = FD->getType();
7213 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007214 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007215 return false;
7216 }
7217 }
7218 return true;
7219}
7220
George Burgess IVe3763372016-12-22 02:50:20 +00007221/// Tests to see if the LValue has a user-specified designator (that isn't
7222/// necessarily valid). Note that this always returns 'true' if the LValue has
7223/// an unsized array as its first designator entry, because there's currently no
7224/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007225static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007226 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007227 return false;
7228
George Burgess IVe3763372016-12-22 02:50:20 +00007229 if (!LVal.Designator.Entries.empty())
7230 return LVal.Designator.isMostDerivedAnUnsizedArray();
7231
George Burgess IVa51c4072015-10-16 01:49:01 +00007232 if (!LVal.InvalidBase)
7233 return true;
7234
George Burgess IVe3763372016-12-22 02:50:20 +00007235 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7236 // the LValueBase.
7237 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7238 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007239}
7240
George Burgess IVe3763372016-12-22 02:50:20 +00007241/// Attempts to detect a user writing into a piece of memory that's impossible
7242/// to figure out the size of by just using types.
7243static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7244 const SubobjectDesignator &Designator = LVal.Designator;
7245 // Notes:
7246 // - Users can only write off of the end when we have an invalid base. Invalid
7247 // bases imply we don't know where the memory came from.
7248 // - We used to be a bit more aggressive here; we'd only be conservative if
7249 // the array at the end was flexible, or if it had 0 or 1 elements. This
7250 // broke some common standard library extensions (PR30346), but was
7251 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7252 // with some sort of whitelist. OTOH, it seems that GCC is always
7253 // conservative with the last element in structs (if it's an array), so our
7254 // current behavior is more compatible than a whitelisting approach would
7255 // be.
7256 return LVal.InvalidBase &&
7257 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7258 Designator.MostDerivedIsArrayElement &&
7259 isDesignatorAtObjectEnd(Ctx, LVal);
7260}
7261
7262/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7263/// Fails if the conversion would cause loss of precision.
7264static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7265 CharUnits &Result) {
7266 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7267 if (Int.ugt(CharUnitsMax))
7268 return false;
7269 Result = CharUnits::fromQuantity(Int.getZExtValue());
7270 return true;
7271}
7272
7273/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7274/// determine how many bytes exist from the beginning of the object to either
7275/// the end of the current subobject, or the end of the object itself, depending
7276/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007277///
George Burgess IVe3763372016-12-22 02:50:20 +00007278/// If this returns false, the value of Result is undefined.
7279static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7280 unsigned Type, const LValue &LVal,
7281 CharUnits &EndOffset) {
7282 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007283
George Burgess IV7fb7e362017-01-03 23:35:19 +00007284 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7285 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7286 return false;
7287 return HandleSizeof(Info, ExprLoc, Ty, Result);
7288 };
7289
George Burgess IVe3763372016-12-22 02:50:20 +00007290 // We want to evaluate the size of the entire object. This is a valid fallback
7291 // for when Type=1 and the designator is invalid, because we're asked for an
7292 // upper-bound.
7293 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7294 // Type=3 wants a lower bound, so we can't fall back to this.
7295 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007296 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007297
7298 llvm::APInt APEndOffset;
7299 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7300 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7301 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7302
7303 if (LVal.InvalidBase)
7304 return false;
7305
7306 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007307 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007308 }
7309
George Burgess IVe3763372016-12-22 02:50:20 +00007310 // We want to evaluate the size of a subobject.
7311 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007312
7313 // The following is a moderately common idiom in C:
7314 //
7315 // struct Foo { int a; char c[1]; };
7316 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7317 // strcpy(&F->c[0], Bar);
7318 //
George Burgess IVe3763372016-12-22 02:50:20 +00007319 // In order to not break too much legacy code, we need to support it.
7320 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7321 // If we can resolve this to an alloc_size call, we can hand that back,
7322 // because we know for certain how many bytes there are to write to.
7323 llvm::APInt APEndOffset;
7324 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7325 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7326 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7327
7328 // If we cannot determine the size of the initial allocation, then we can't
7329 // given an accurate upper-bound. However, we are still able to give
7330 // conservative lower-bounds for Type=3.
7331 if (Type == 1)
7332 return false;
7333 }
7334
7335 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007336 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007337 return false;
7338
George Burgess IVe3763372016-12-22 02:50:20 +00007339 // According to the GCC documentation, we want the size of the subobject
7340 // denoted by the pointer. But that's not quite right -- what we actually
7341 // want is the size of the immediately-enclosing array, if there is one.
7342 int64_t ElemsRemaining;
7343 if (Designator.MostDerivedIsArrayElement &&
7344 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7345 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7346 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7347 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7348 } else {
7349 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7350 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007351
George Burgess IVe3763372016-12-22 02:50:20 +00007352 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7353 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007354}
7355
George Burgess IVe3763372016-12-22 02:50:20 +00007356/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7357/// returns true and stores the result in @p Size.
7358///
7359/// If @p WasError is non-null, this will report whether the failure to evaluate
7360/// is to be treated as an Error in IntExprEvaluator.
7361static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7362 EvalInfo &Info, uint64_t &Size) {
7363 // Determine the denoted object.
7364 LValue LVal;
7365 {
7366 // The operand of __builtin_object_size is never evaluated for side-effects.
7367 // If there are any, but we can determine the pointed-to object anyway, then
7368 // ignore the side-effects.
7369 SpeculativeEvaluationRAII SpeculativeEval(Info);
7370 FoldOffsetRAII Fold(Info);
7371
7372 if (E->isGLValue()) {
7373 // It's possible for us to be given GLValues if we're called via
7374 // Expr::tryEvaluateObjectSize.
7375 APValue RVal;
7376 if (!EvaluateAsRValue(Info, E, RVal))
7377 return false;
7378 LVal.setFrom(Info.Ctx, RVal);
7379 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info))
7380 return false;
7381 }
7382
7383 // If we point to before the start of the object, there are no accessible
7384 // bytes.
7385 if (LVal.getLValueOffset().isNegative()) {
7386 Size = 0;
7387 return true;
7388 }
7389
7390 CharUnits EndOffset;
7391 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7392 return false;
7393
7394 // If we've fallen outside of the end offset, just pretend there's nothing to
7395 // write to/read from.
7396 if (EndOffset <= LVal.getLValueOffset())
7397 Size = 0;
7398 else
7399 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7400 return true;
John McCall95007602010-05-10 23:27:23 +00007401}
7402
Peter Collingbournee9200682011-05-13 03:29:01 +00007403bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007404 if (unsigned BuiltinOp = E->getBuiltinCallee())
7405 return VisitBuiltinCallExpr(E, BuiltinOp);
7406
7407 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7408}
7409
7410bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7411 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007412 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007413 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007414 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007415
7416 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007417 // The type was checked when we built the expression.
7418 unsigned Type =
7419 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7420 assert(Type <= 3 && "unexpected type");
7421
George Burgess IVe3763372016-12-22 02:50:20 +00007422 uint64_t Size;
7423 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7424 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007425
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007426 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007427 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007428
Richard Smith01ade172012-05-23 04:13:20 +00007429 // Expression had no side effects, but we couldn't statically determine the
7430 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007431 switch (Info.EvalMode) {
7432 case EvalInfo::EM_ConstantExpression:
7433 case EvalInfo::EM_PotentialConstantExpression:
7434 case EvalInfo::EM_ConstantFold:
7435 case EvalInfo::EM_EvaluateForOverflow:
7436 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007437 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007438 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007439 return Error(E);
7440 case EvalInfo::EM_ConstantExpressionUnevaluated:
7441 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007442 // Reduce it to a constant now.
7443 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007444 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007445
7446 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007447 }
7448
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007449 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007450 case Builtin::BI__builtin_bswap32:
7451 case Builtin::BI__builtin_bswap64: {
7452 APSInt Val;
7453 if (!EvaluateInteger(E->getArg(0), Val, Info))
7454 return false;
7455
7456 return Success(Val.byteSwap(), E);
7457 }
7458
Richard Smith8889a3d2013-06-13 06:26:32 +00007459 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007460 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007461
7462 // FIXME: BI__builtin_clrsb
7463 // FIXME: BI__builtin_clrsbl
7464 // FIXME: BI__builtin_clrsbll
7465
Richard Smith80b3c8e2013-06-13 05:04:16 +00007466 case Builtin::BI__builtin_clz:
7467 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007468 case Builtin::BI__builtin_clzll:
7469 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007470 APSInt Val;
7471 if (!EvaluateInteger(E->getArg(0), Val, Info))
7472 return false;
7473 if (!Val)
7474 return Error(E);
7475
7476 return Success(Val.countLeadingZeros(), E);
7477 }
7478
Richard Smith8889a3d2013-06-13 06:26:32 +00007479 case Builtin::BI__builtin_constant_p:
7480 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7481
Richard Smith80b3c8e2013-06-13 05:04:16 +00007482 case Builtin::BI__builtin_ctz:
7483 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007484 case Builtin::BI__builtin_ctzll:
7485 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007486 APSInt Val;
7487 if (!EvaluateInteger(E->getArg(0), Val, Info))
7488 return false;
7489 if (!Val)
7490 return Error(E);
7491
7492 return Success(Val.countTrailingZeros(), E);
7493 }
7494
Richard Smith8889a3d2013-06-13 06:26:32 +00007495 case Builtin::BI__builtin_eh_return_data_regno: {
7496 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7497 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7498 return Success(Operand, E);
7499 }
7500
7501 case Builtin::BI__builtin_expect:
7502 return Visit(E->getArg(0));
7503
7504 case Builtin::BI__builtin_ffs:
7505 case Builtin::BI__builtin_ffsl:
7506 case Builtin::BI__builtin_ffsll: {
7507 APSInt Val;
7508 if (!EvaluateInteger(E->getArg(0), Val, Info))
7509 return false;
7510
7511 unsigned N = Val.countTrailingZeros();
7512 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7513 }
7514
7515 case Builtin::BI__builtin_fpclassify: {
7516 APFloat Val(0.0);
7517 if (!EvaluateFloat(E->getArg(5), Val, Info))
7518 return false;
7519 unsigned Arg;
7520 switch (Val.getCategory()) {
7521 case APFloat::fcNaN: Arg = 0; break;
7522 case APFloat::fcInfinity: Arg = 1; break;
7523 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7524 case APFloat::fcZero: Arg = 4; break;
7525 }
7526 return Visit(E->getArg(Arg));
7527 }
7528
7529 case Builtin::BI__builtin_isinf_sign: {
7530 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007531 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007532 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7533 }
7534
Richard Smithea3019d2013-10-15 19:07:14 +00007535 case Builtin::BI__builtin_isinf: {
7536 APFloat Val(0.0);
7537 return EvaluateFloat(E->getArg(0), Val, Info) &&
7538 Success(Val.isInfinity() ? 1 : 0, E);
7539 }
7540
7541 case Builtin::BI__builtin_isfinite: {
7542 APFloat Val(0.0);
7543 return EvaluateFloat(E->getArg(0), Val, Info) &&
7544 Success(Val.isFinite() ? 1 : 0, E);
7545 }
7546
7547 case Builtin::BI__builtin_isnan: {
7548 APFloat Val(0.0);
7549 return EvaluateFloat(E->getArg(0), Val, Info) &&
7550 Success(Val.isNaN() ? 1 : 0, E);
7551 }
7552
7553 case Builtin::BI__builtin_isnormal: {
7554 APFloat Val(0.0);
7555 return EvaluateFloat(E->getArg(0), Val, Info) &&
7556 Success(Val.isNormal() ? 1 : 0, E);
7557 }
7558
Richard Smith8889a3d2013-06-13 06:26:32 +00007559 case Builtin::BI__builtin_parity:
7560 case Builtin::BI__builtin_parityl:
7561 case Builtin::BI__builtin_parityll: {
7562 APSInt Val;
7563 if (!EvaluateInteger(E->getArg(0), Val, Info))
7564 return false;
7565
7566 return Success(Val.countPopulation() % 2, E);
7567 }
7568
Richard Smith80b3c8e2013-06-13 05:04:16 +00007569 case Builtin::BI__builtin_popcount:
7570 case Builtin::BI__builtin_popcountl:
7571 case Builtin::BI__builtin_popcountll: {
7572 APSInt Val;
7573 if (!EvaluateInteger(E->getArg(0), Val, Info))
7574 return false;
7575
7576 return Success(Val.countPopulation(), E);
7577 }
7578
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007579 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007580 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007581 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007582 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007583 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007584 << /*isConstexpr*/0 << /*isConstructor*/0
7585 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007586 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007587 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007588 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007589 case Builtin::BI__builtin_strlen:
7590 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007591 // As an extension, we support __builtin_strlen() as a constant expression,
7592 // and support folding strlen() to a constant.
7593 LValue String;
7594 if (!EvaluatePointer(E->getArg(0), String, Info))
7595 return false;
7596
Richard Smith8110c9d2016-11-29 19:45:17 +00007597 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7598
Richard Smithe6c19f22013-11-15 02:10:04 +00007599 // Fast path: if it's a string literal, search the string value.
7600 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7601 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007602 // The string literal may have embedded null characters. Find the first
7603 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007604 StringRef Str = S->getBytes();
7605 int64_t Off = String.Offset.getQuantity();
7606 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007607 S->getCharByteWidth() == 1 &&
7608 // FIXME: Add fast-path for wchar_t too.
7609 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007610 Str = Str.substr(Off);
7611
7612 StringRef::size_type Pos = Str.find(0);
7613 if (Pos != StringRef::npos)
7614 Str = Str.substr(0, Pos);
7615
7616 return Success(Str.size(), E);
7617 }
7618
7619 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007620 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007621
7622 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007623 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7624 APValue Char;
7625 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7626 !Char.isInt())
7627 return false;
7628 if (!Char.getInt())
7629 return Success(Strlen, E);
7630 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7631 return false;
7632 }
7633 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007634
Richard Smithe151bab2016-11-11 23:43:35 +00007635 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007636 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007637 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007638 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007639 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007640 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007641 // A call to strlen is not a constant expression.
7642 if (Info.getLangOpts().CPlusPlus11)
7643 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7644 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007645 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007646 else
7647 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7648 // Fall through.
7649 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007650 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007651 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007652 case Builtin::BI__builtin_wcsncmp:
7653 case Builtin::BI__builtin_memcmp:
7654 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007655 LValue String1, String2;
7656 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7657 !EvaluatePointer(E->getArg(1), String2, Info))
7658 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007659
7660 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7661
Richard Smithe151bab2016-11-11 23:43:35 +00007662 uint64_t MaxLength = uint64_t(-1);
7663 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007664 BuiltinOp != Builtin::BIwcscmp &&
7665 BuiltinOp != Builtin::BI__builtin_strcmp &&
7666 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007667 APSInt N;
7668 if (!EvaluateInteger(E->getArg(2), N, Info))
7669 return false;
7670 MaxLength = N.getExtValue();
7671 }
7672 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007673 BuiltinOp != Builtin::BIwmemcmp &&
7674 BuiltinOp != Builtin::BI__builtin_memcmp &&
7675 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007676 for (; MaxLength; --MaxLength) {
7677 APValue Char1, Char2;
7678 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7679 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7680 !Char1.isInt() || !Char2.isInt())
7681 return false;
7682 if (Char1.getInt() != Char2.getInt())
7683 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7684 if (StopAtNull && !Char1.getInt())
7685 return Success(0, E);
7686 assert(!(StopAtNull && !Char2.getInt()));
7687 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7688 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7689 return false;
7690 }
7691 // We hit the strncmp / memcmp limit.
7692 return Success(0, E);
7693 }
7694
Richard Smith01ba47d2012-04-13 00:45:38 +00007695 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007696 case Builtin::BI__atomic_is_lock_free:
7697 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007698 APSInt SizeVal;
7699 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7700 return false;
7701
7702 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7703 // of two less than the maximum inline atomic width, we know it is
7704 // lock-free. If the size isn't a power of two, or greater than the
7705 // maximum alignment where we promote atomics, we know it is not lock-free
7706 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7707 // the answer can only be determined at runtime; for example, 16-byte
7708 // atomics have lock-free implementations on some, but not all,
7709 // x86-64 processors.
7710
7711 // Check power-of-two.
7712 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007713 if (Size.isPowerOfTwo()) {
7714 // Check against inlining width.
7715 unsigned InlineWidthBits =
7716 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7717 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7718 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7719 Size == CharUnits::One() ||
7720 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7721 Expr::NPC_NeverValueDependent))
7722 // OK, we will inline appropriately-aligned operations of this size,
7723 // and _Atomic(T) is appropriately-aligned.
7724 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007725
Richard Smith01ba47d2012-04-13 00:45:38 +00007726 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7727 castAs<PointerType>()->getPointeeType();
7728 if (!PointeeType->isIncompleteType() &&
7729 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7730 // OK, we will inline operations on this object.
7731 return Success(1, E);
7732 }
7733 }
7734 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007735
Richard Smith01ba47d2012-04-13 00:45:38 +00007736 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7737 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007738 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007739 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007740}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007741
Richard Smith8b3497e2011-10-31 01:37:14 +00007742static bool HasSameBase(const LValue &A, const LValue &B) {
7743 if (!A.getLValueBase())
7744 return !B.getLValueBase();
7745 if (!B.getLValueBase())
7746 return false;
7747
Richard Smithce40ad62011-11-12 22:28:03 +00007748 if (A.getLValueBase().getOpaqueValue() !=
7749 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007750 const Decl *ADecl = GetLValueBaseDecl(A);
7751 if (!ADecl)
7752 return false;
7753 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007754 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007755 return false;
7756 }
7757
7758 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007759 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007760}
7761
Richard Smithd20f1e62014-10-21 23:01:04 +00007762/// \brief Determine whether this is a pointer past the end of the complete
7763/// object referred to by the lvalue.
7764static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7765 const LValue &LV) {
7766 // A null pointer can be viewed as being "past the end" but we don't
7767 // choose to look at it that way here.
7768 if (!LV.getLValueBase())
7769 return false;
7770
7771 // If the designator is valid and refers to a subobject, we're not pointing
7772 // past the end.
7773 if (!LV.getLValueDesignator().Invalid &&
7774 !LV.getLValueDesignator().isOnePastTheEnd())
7775 return false;
7776
David Majnemerc378ca52015-08-29 08:32:55 +00007777 // A pointer to an incomplete type might be past-the-end if the type's size is
7778 // zero. We cannot tell because the type is incomplete.
7779 QualType Ty = getType(LV.getLValueBase());
7780 if (Ty->isIncompleteType())
7781 return true;
7782
Richard Smithd20f1e62014-10-21 23:01:04 +00007783 // We're a past-the-end pointer if we point to the byte after the object,
7784 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007785 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007786 return LV.getLValueOffset() == Size;
7787}
7788
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007789namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007790
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007791/// \brief Data recursive integer evaluator of certain binary operators.
7792///
7793/// We use a data recursive algorithm for binary operators so that we are able
7794/// to handle extreme cases of chained binary operators without causing stack
7795/// overflow.
7796class DataRecursiveIntBinOpEvaluator {
7797 struct EvalResult {
7798 APValue Val;
7799 bool Failed;
7800
7801 EvalResult() : Failed(false) { }
7802
7803 void swap(EvalResult &RHS) {
7804 Val.swap(RHS.Val);
7805 Failed = RHS.Failed;
7806 RHS.Failed = false;
7807 }
7808 };
7809
7810 struct Job {
7811 const Expr *E;
7812 EvalResult LHSResult; // meaningful only for binary operator expression.
7813 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007814
David Blaikie73726062015-08-12 23:09:24 +00007815 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007816 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007817
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007818 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007819 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007820 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007821
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007822 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007823 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007824 };
7825
7826 SmallVector<Job, 16> Queue;
7827
7828 IntExprEvaluator &IntEval;
7829 EvalInfo &Info;
7830 APValue &FinalResult;
7831
7832public:
7833 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7834 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7835
7836 /// \brief True if \param E is a binary operator that we are going to handle
7837 /// data recursively.
7838 /// We handle binary operators that are comma, logical, or that have operands
7839 /// with integral or enumeration type.
7840 static bool shouldEnqueue(const BinaryOperator *E) {
7841 return E->getOpcode() == BO_Comma ||
7842 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007843 (E->isRValue() &&
7844 E->getType()->isIntegralOrEnumerationType() &&
7845 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007846 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007847 }
7848
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007849 bool Traverse(const BinaryOperator *E) {
7850 enqueue(E);
7851 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007852 while (!Queue.empty())
7853 process(PrevResult);
7854
7855 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007856
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007857 FinalResult.swap(PrevResult.Val);
7858 return true;
7859 }
7860
7861private:
7862 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7863 return IntEval.Success(Value, E, Result);
7864 }
7865 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7866 return IntEval.Success(Value, E, Result);
7867 }
7868 bool Error(const Expr *E) {
7869 return IntEval.Error(E);
7870 }
7871 bool Error(const Expr *E, diag::kind D) {
7872 return IntEval.Error(E, D);
7873 }
7874
7875 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7876 return Info.CCEDiag(E, D);
7877 }
7878
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007879 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7880 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007881 bool &SuppressRHSDiags);
7882
7883 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7884 const BinaryOperator *E, APValue &Result);
7885
7886 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7887 Result.Failed = !Evaluate(Result.Val, Info, E);
7888 if (Result.Failed)
7889 Result.Val = APValue();
7890 }
7891
Richard Trieuba4d0872012-03-21 23:30:30 +00007892 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007893
7894 void enqueue(const Expr *E) {
7895 E = E->IgnoreParens();
7896 Queue.resize(Queue.size()+1);
7897 Queue.back().E = E;
7898 Queue.back().Kind = Job::AnyExprKind;
7899 }
7900};
7901
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007902}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007903
7904bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007905 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007906 bool &SuppressRHSDiags) {
7907 if (E->getOpcode() == BO_Comma) {
7908 // Ignore LHS but note if we could not evaluate it.
7909 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007910 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007911 return true;
7912 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007913
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007914 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007915 bool LHSAsBool;
7916 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007917 // We were able to evaluate the LHS, see if we can get away with not
7918 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007919 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7920 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007921 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007922 }
7923 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007924 LHSResult.Failed = true;
7925
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007926 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00007927 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007928 if (!Info.noteSideEffect())
7929 return false;
7930
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007931 // We can't evaluate the LHS; however, sometimes the result
7932 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7933 // Don't ignore RHS and suppress diagnostics from this arm.
7934 SuppressRHSDiags = true;
7935 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007936
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007937 return true;
7938 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007939
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007940 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7941 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007942
George Burgess IVa145e252016-05-25 22:38:36 +00007943 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007944 return false; // Ignore RHS;
7945
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007946 return true;
7947}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007948
Richard Smithd6cc1982017-01-31 02:23:02 +00007949static void addOrSubLValueAsInteger(APValue &LVal, APSInt Index, bool IsSub) {
7950 // Compute the new offset in the appropriate width, wrapping at 64 bits.
7951 // FIXME: When compiling for a 32-bit target, we should use 32-bit
7952 // offsets.
7953 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
7954 CharUnits &Offset = LVal.getLValueOffset();
7955 uint64_t Offset64 = Offset.getQuantity();
7956 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
7957 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
7958 : Offset64 + Index64);
7959}
7960
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007961bool DataRecursiveIntBinOpEvaluator::
7962 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7963 const BinaryOperator *E, APValue &Result) {
7964 if (E->getOpcode() == BO_Comma) {
7965 if (RHSResult.Failed)
7966 return false;
7967 Result = RHSResult.Val;
7968 return true;
7969 }
7970
7971 if (E->isLogicalOp()) {
7972 bool lhsResult, rhsResult;
7973 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7974 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7975
7976 if (LHSIsOK) {
7977 if (RHSIsOK) {
7978 if (E->getOpcode() == BO_LOr)
7979 return Success(lhsResult || rhsResult, E, Result);
7980 else
7981 return Success(lhsResult && rhsResult, E, Result);
7982 }
7983 } else {
7984 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007985 // We can't evaluate the LHS; however, sometimes the result
7986 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7987 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007988 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007989 }
7990 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007991
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007992 return false;
7993 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007994
7995 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7996 E->getRHS()->getType()->isIntegralOrEnumerationType());
7997
7998 if (LHSResult.Failed || RHSResult.Failed)
7999 return false;
8000
8001 const APValue &LHSVal = LHSResult.Val;
8002 const APValue &RHSVal = RHSResult.Val;
8003
8004 // Handle cases like (unsigned long)&a + 4.
8005 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8006 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008007 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008008 return true;
8009 }
8010
8011 // Handle cases like 4 + (unsigned long)&a
8012 if (E->getOpcode() == BO_Add &&
8013 RHSVal.isLValue() && LHSVal.isInt()) {
8014 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008015 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008016 return true;
8017 }
8018
8019 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8020 // Handle (intptr_t)&&A - (intptr_t)&&B.
8021 if (!LHSVal.getLValueOffset().isZero() ||
8022 !RHSVal.getLValueOffset().isZero())
8023 return false;
8024 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8025 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8026 if (!LHSExpr || !RHSExpr)
8027 return false;
8028 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8029 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8030 if (!LHSAddrExpr || !RHSAddrExpr)
8031 return false;
8032 // Make sure both labels come from the same function.
8033 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8034 RHSAddrExpr->getLabel()->getDeclContext())
8035 return false;
8036 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8037 return true;
8038 }
Richard Smith43e77732013-05-07 04:50:00 +00008039
8040 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008041 if (!LHSVal.isInt() || !RHSVal.isInt())
8042 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008043
8044 // Set up the width and signedness manually, in case it can't be deduced
8045 // from the operation we're performing.
8046 // FIXME: Don't do this in the cases where we can deduce it.
8047 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8048 E->getType()->isUnsignedIntegerOrEnumerationType());
8049 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8050 RHSVal.getInt(), Value))
8051 return false;
8052 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008053}
8054
Richard Trieuba4d0872012-03-21 23:30:30 +00008055void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008056 Job &job = Queue.back();
8057
8058 switch (job.Kind) {
8059 case Job::AnyExprKind: {
8060 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8061 if (shouldEnqueue(Bop)) {
8062 job.Kind = Job::BinOpKind;
8063 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008064 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008065 }
8066 }
8067
8068 EvaluateExpr(job.E, Result);
8069 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008070 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008071 }
8072
8073 case Job::BinOpKind: {
8074 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008075 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008076 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008077 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008078 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008079 }
8080 if (SuppressRHSDiags)
8081 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008082 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008083 job.Kind = Job::BinOpVisitedLHSKind;
8084 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008085 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008086 }
8087
8088 case Job::BinOpVisitedLHSKind: {
8089 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8090 EvalResult RHS;
8091 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008092 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008093 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008094 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008095 }
8096 }
8097
8098 llvm_unreachable("Invalid Job::Kind!");
8099}
8100
George Burgess IV8c892b52016-05-25 22:31:54 +00008101namespace {
8102/// Used when we determine that we should fail, but can keep evaluating prior to
8103/// noting that we had a failure.
8104class DelayedNoteFailureRAII {
8105 EvalInfo &Info;
8106 bool NoteFailure;
8107
8108public:
8109 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8110 : Info(Info), NoteFailure(NoteFailure) {}
8111 ~DelayedNoteFailureRAII() {
8112 if (NoteFailure) {
8113 bool ContinueAfterFailure = Info.noteFailure();
8114 (void)ContinueAfterFailure;
8115 assert(ContinueAfterFailure &&
8116 "Shouldn't have kept evaluating on failure.");
8117 }
8118 }
8119};
8120}
8121
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008122bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008123 // We don't call noteFailure immediately because the assignment happens after
8124 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008125 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008126 return Error(E);
8127
George Burgess IV8c892b52016-05-25 22:31:54 +00008128 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008129 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8130 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008131
Anders Carlssonacc79812008-11-16 07:17:21 +00008132 QualType LHSTy = E->getLHS()->getType();
8133 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008134
Chandler Carruthb29a7432014-10-11 11:03:30 +00008135 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008136 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008137 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008138 if (E->isAssignmentOp()) {
8139 LValue LV;
8140 EvaluateLValue(E->getLHS(), LV, Info);
8141 LHSOK = false;
8142 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008143 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8144 if (LHSOK) {
8145 LHS.makeComplexFloat();
8146 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8147 }
8148 } else {
8149 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8150 }
George Burgess IVa145e252016-05-25 22:38:36 +00008151 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008152 return false;
8153
Chandler Carruthb29a7432014-10-11 11:03:30 +00008154 if (E->getRHS()->getType()->isRealFloatingType()) {
8155 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8156 return false;
8157 RHS.makeComplexFloat();
8158 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8159 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008160 return false;
8161
8162 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008163 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008164 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008165 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008166 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8167
John McCalle3027922010-08-25 11:45:40 +00008168 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008169 return Success((CR_r == APFloat::cmpEqual &&
8170 CR_i == APFloat::cmpEqual), E);
8171 else {
John McCalle3027922010-08-25 11:45:40 +00008172 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008173 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008174 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008175 CR_r == APFloat::cmpLessThan ||
8176 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008177 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008178 CR_i == APFloat::cmpLessThan ||
8179 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008180 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008181 } else {
John McCalle3027922010-08-25 11:45:40 +00008182 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008183 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8184 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8185 else {
John McCalle3027922010-08-25 11:45:40 +00008186 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008187 "Invalid compex comparison.");
8188 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8189 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8190 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008191 }
8192 }
Mike Stump11289f42009-09-09 15:08:12 +00008193
Anders Carlssonacc79812008-11-16 07:17:21 +00008194 if (LHSTy->isRealFloatingType() &&
8195 RHSTy->isRealFloatingType()) {
8196 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008197
Richard Smith253c2a32012-01-27 01:14:48 +00008198 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008199 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008200 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008201
Richard Smith253c2a32012-01-27 01:14:48 +00008202 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008203 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008204
Anders Carlssonacc79812008-11-16 07:17:21 +00008205 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008206
Anders Carlssonacc79812008-11-16 07:17:21 +00008207 switch (E->getOpcode()) {
8208 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008209 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008210 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008211 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008212 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008213 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008214 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008215 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008216 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008217 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008218 E);
John McCalle3027922010-08-25 11:45:40 +00008219 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008220 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008221 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008222 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008223 || CR == APFloat::cmpLessThan
8224 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008225 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008226 }
Mike Stump11289f42009-09-09 15:08:12 +00008227
Eli Friedmana38da572009-04-28 19:17:36 +00008228 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008229 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008230 LValue LHSValue, RHSValue;
8231
8232 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008233 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008234 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008235
Richard Smith253c2a32012-01-27 01:14:48 +00008236 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008237 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008238
Richard Smith8b3497e2011-10-31 01:37:14 +00008239 // Reject differing bases from the normal codepath; we special-case
8240 // comparisons to null.
8241 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008242 if (E->getOpcode() == BO_Sub) {
8243 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008244 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008245 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008246 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008247 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008248 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008249 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008250 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8251 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8252 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008253 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008254 // Make sure both labels come from the same function.
8255 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8256 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008257 return Error(E);
8258 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008259 }
Richard Smith83c68212011-10-31 05:11:32 +00008260 // Inequalities and subtractions between unrelated pointers have
8261 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008262 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008263 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008264 // A constant address may compare equal to the address of a symbol.
8265 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008266 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008267 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8268 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008269 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008270 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008271 // distinct addresses. In clang, the result of such a comparison is
8272 // unspecified, so it is not a constant expression. However, we do know
8273 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008274 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8275 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008276 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008277 // We can't tell whether weak symbols will end up pointing to the same
8278 // object.
8279 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008280 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008281 // We can't compare the address of the start of one object with the
8282 // past-the-end address of another object, per C++ DR1652.
8283 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8284 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8285 (RHSValue.Base && RHSValue.Offset.isZero() &&
8286 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8287 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008288 // We can't tell whether an object is at the same address as another
8289 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008290 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8291 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008292 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008293 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008294 // (Note that clang defaults to -fmerge-all-constants, which can
8295 // lead to inconsistent results for comparisons involving the address
8296 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008297 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008298 }
Eli Friedman64004332009-03-23 04:38:34 +00008299
Richard Smith1b470412012-02-01 08:10:20 +00008300 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8301 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8302
Richard Smith84f6dcf2012-02-02 01:16:57 +00008303 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8304 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8305
John McCalle3027922010-08-25 11:45:40 +00008306 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008307 // C++11 [expr.add]p6:
8308 // Unless both pointers point to elements of the same array object, or
8309 // one past the last element of the array object, the behavior is
8310 // undefined.
8311 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8312 !AreElementsOfSameArray(getType(LHSValue.Base),
8313 LHSDesignator, RHSDesignator))
8314 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8315
Chris Lattner882bdf22010-04-20 17:13:14 +00008316 QualType Type = E->getLHS()->getType();
8317 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008318
Richard Smithd62306a2011-11-10 06:34:14 +00008319 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008320 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008321 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008322
Richard Smith84c6b3d2013-09-10 21:34:14 +00008323 // As an extension, a type may have zero size (empty struct or union in
8324 // C, array of zero length). Pointer subtraction in such cases has
8325 // undefined behavior, so is not constant.
8326 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008327 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008328 << ElementType;
8329 return false;
8330 }
8331
Richard Smith1b470412012-02-01 08:10:20 +00008332 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8333 // and produce incorrect results when it overflows. Such behavior
8334 // appears to be non-conforming, but is common, so perhaps we should
8335 // assume the standard intended for such cases to be undefined behavior
8336 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008337
Richard Smith1b470412012-02-01 08:10:20 +00008338 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8339 // overflow in the final conversion to ptrdiff_t.
8340 APSInt LHS(
8341 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8342 APSInt RHS(
8343 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8344 APSInt ElemSize(
8345 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8346 APSInt TrueResult = (LHS - RHS) / ElemSize;
8347 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8348
Richard Smith0c6124b2015-12-03 01:36:22 +00008349 if (Result.extend(65) != TrueResult &&
8350 !HandleOverflow(Info, E, TrueResult, E->getType()))
8351 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008352 return Success(Result, E);
8353 }
Richard Smithde21b242012-01-31 06:41:30 +00008354
8355 // C++11 [expr.rel]p3:
8356 // Pointers to void (after pointer conversions) can be compared, with a
8357 // result defined as follows: If both pointers represent the same
8358 // address or are both the null pointer value, the result is true if the
8359 // operator is <= or >= and false otherwise; otherwise the result is
8360 // unspecified.
8361 // We interpret this as applying to pointers to *cv* void.
8362 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008363 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008364 CCEDiag(E, diag::note_constexpr_void_comparison);
8365
Richard Smith84f6dcf2012-02-02 01:16:57 +00008366 // C++11 [expr.rel]p2:
8367 // - If two pointers point to non-static data members of the same object,
8368 // or to subobjects or array elements fo such members, recursively, the
8369 // pointer to the later declared member compares greater provided the
8370 // two members have the same access control and provided their class is
8371 // not a union.
8372 // [...]
8373 // - Otherwise pointer comparisons are unspecified.
8374 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8375 E->isRelationalOp()) {
8376 bool WasArrayIndex;
8377 unsigned Mismatch =
8378 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8379 RHSDesignator, WasArrayIndex);
8380 // At the point where the designators diverge, the comparison has a
8381 // specified value if:
8382 // - we are comparing array indices
8383 // - we are comparing fields of a union, or fields with the same access
8384 // Otherwise, the result is unspecified and thus the comparison is not a
8385 // constant expression.
8386 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8387 Mismatch < RHSDesignator.Entries.size()) {
8388 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8389 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8390 if (!LF && !RF)
8391 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8392 else if (!LF)
8393 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8394 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8395 << RF->getParent() << RF;
8396 else if (!RF)
8397 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8398 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8399 << LF->getParent() << LF;
8400 else if (!LF->getParent()->isUnion() &&
8401 LF->getAccess() != RF->getAccess())
8402 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8403 << LF << LF->getAccess() << RF << RF->getAccess()
8404 << LF->getParent();
8405 }
8406 }
8407
Eli Friedman6c31cb42012-04-16 04:30:08 +00008408 // The comparison here must be unsigned, and performed with the same
8409 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008410 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8411 uint64_t CompareLHS = LHSOffset.getQuantity();
8412 uint64_t CompareRHS = RHSOffset.getQuantity();
8413 assert(PtrSize <= 64 && "Unexpected pointer width");
8414 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8415 CompareLHS &= Mask;
8416 CompareRHS &= Mask;
8417
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008418 // If there is a base and this is a relational operator, we can only
8419 // compare pointers within the object in question; otherwise, the result
8420 // depends on where the object is located in memory.
8421 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8422 QualType BaseTy = getType(LHSValue.Base);
8423 if (BaseTy->isIncompleteType())
8424 return Error(E);
8425 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8426 uint64_t OffsetLimit = Size.getQuantity();
8427 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8428 return Error(E);
8429 }
8430
Richard Smith8b3497e2011-10-31 01:37:14 +00008431 switch (E->getOpcode()) {
8432 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008433 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8434 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8435 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8436 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8437 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8438 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008439 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008440 }
8441 }
Richard Smith7bb00672012-02-01 01:42:44 +00008442
8443 if (LHSTy->isMemberPointerType()) {
8444 assert(E->isEqualityOp() && "unexpected member pointer operation");
8445 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8446
8447 MemberPtr LHSValue, RHSValue;
8448
8449 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008450 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008451 return false;
8452
8453 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8454 return false;
8455
8456 // C++11 [expr.eq]p2:
8457 // If both operands are null, they compare equal. Otherwise if only one is
8458 // null, they compare unequal.
8459 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8460 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8461 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8462 }
8463
8464 // Otherwise if either is a pointer to a virtual member function, the
8465 // result is unspecified.
8466 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8467 if (MD->isVirtual())
8468 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8469 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8470 if (MD->isVirtual())
8471 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8472
8473 // Otherwise they compare equal if and only if they would refer to the
8474 // same member of the same most derived object or the same subobject if
8475 // they were dereferenced with a hypothetical object of the associated
8476 // class type.
8477 bool Equal = LHSValue == RHSValue;
8478 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8479 }
8480
Richard Smithab44d9b2012-02-14 22:35:28 +00008481 if (LHSTy->isNullPtrType()) {
8482 assert(E->isComparisonOp() && "unexpected nullptr operation");
8483 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8484 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8485 // are compared, the result is true of the operator is <=, >= or ==, and
8486 // false otherwise.
8487 BinaryOperator::Opcode Opcode = E->getOpcode();
8488 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8489 }
8490
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008491 assert((!LHSTy->isIntegralOrEnumerationType() ||
8492 !RHSTy->isIntegralOrEnumerationType()) &&
8493 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8494 // We can't continue from here for non-integral types.
8495 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008496}
8497
Peter Collingbournee190dee2011-03-11 19:24:49 +00008498/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8499/// a result as the expression's type.
8500bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8501 const UnaryExprOrTypeTraitExpr *E) {
8502 switch(E->getKind()) {
8503 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008504 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008505 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008506 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008507 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008508 }
Eli Friedman64004332009-03-23 04:38:34 +00008509
Peter Collingbournee190dee2011-03-11 19:24:49 +00008510 case UETT_VecStep: {
8511 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008512
Peter Collingbournee190dee2011-03-11 19:24:49 +00008513 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008514 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008515
Peter Collingbournee190dee2011-03-11 19:24:49 +00008516 // The vec_step built-in functions that take a 3-component
8517 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8518 if (n == 3)
8519 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008520
Peter Collingbournee190dee2011-03-11 19:24:49 +00008521 return Success(n, E);
8522 } else
8523 return Success(1, E);
8524 }
8525
8526 case UETT_SizeOf: {
8527 QualType SrcTy = E->getTypeOfArgument();
8528 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8529 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008530 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8531 SrcTy = Ref->getPointeeType();
8532
Richard Smithd62306a2011-11-10 06:34:14 +00008533 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008534 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008535 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008536 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008537 }
Alexey Bataev00396512015-07-02 03:40:19 +00008538 case UETT_OpenMPRequiredSimdAlign:
8539 assert(E->isArgumentType());
8540 return Success(
8541 Info.Ctx.toCharUnitsFromBits(
8542 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8543 .getQuantity(),
8544 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008545 }
8546
8547 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008548}
8549
Peter Collingbournee9200682011-05-13 03:29:01 +00008550bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008551 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008552 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008553 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008554 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008555 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008556 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008557 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008558 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008559 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008560 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008561 APSInt IdxResult;
8562 if (!EvaluateInteger(Idx, IdxResult, Info))
8563 return false;
8564 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8565 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008566 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008567 CurrentType = AT->getElementType();
8568 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8569 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008570 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008571 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008572
James Y Knight7281c352015-12-29 22:31:18 +00008573 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008574 FieldDecl *MemberDecl = ON.getField();
8575 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008576 if (!RT)
8577 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008578 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008579 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008580 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008581 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008582 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008583 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008584 CurrentType = MemberDecl->getType().getNonReferenceType();
8585 break;
8586 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008587
James Y Knight7281c352015-12-29 22:31:18 +00008588 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008589 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008590
James Y Knight7281c352015-12-29 22:31:18 +00008591 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008592 CXXBaseSpecifier *BaseSpec = ON.getBase();
8593 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008594 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008595
8596 // Find the layout of the class whose base we are looking into.
8597 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008598 if (!RT)
8599 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008600 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008601 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008602 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8603
8604 // Find the base class itself.
8605 CurrentType = BaseSpec->getType();
8606 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8607 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008608 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008609
8610 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008611 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008612 break;
8613 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008614 }
8615 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008616 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008617}
8618
Chris Lattnere13042c2008-07-11 19:10:17 +00008619bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008620 switch (E->getOpcode()) {
8621 default:
8622 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8623 // See C99 6.6p3.
8624 return Error(E);
8625 case UO_Extension:
8626 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8627 // If so, we could clear the diagnostic ID.
8628 return Visit(E->getSubExpr());
8629 case UO_Plus:
8630 // The result is just the value.
8631 return Visit(E->getSubExpr());
8632 case UO_Minus: {
8633 if (!Visit(E->getSubExpr()))
8634 return false;
8635 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008636 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008637 if (Value.isSigned() && Value.isMinSignedValue() &&
8638 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8639 E->getType()))
8640 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008641 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008642 }
8643 case UO_Not: {
8644 if (!Visit(E->getSubExpr()))
8645 return false;
8646 if (!Result.isInt()) return Error(E);
8647 return Success(~Result.getInt(), E);
8648 }
8649 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008650 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008651 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008652 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008653 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008654 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008655 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008656}
Mike Stump11289f42009-09-09 15:08:12 +00008657
Chris Lattner477c4be2008-07-12 01:15:53 +00008658/// HandleCast - This is used to evaluate implicit or explicit casts where the
8659/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008660bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8661 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008662 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008663 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008664
Eli Friedmanc757de22011-03-25 00:43:55 +00008665 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008666 case CK_BaseToDerived:
8667 case CK_DerivedToBase:
8668 case CK_UncheckedDerivedToBase:
8669 case CK_Dynamic:
8670 case CK_ToUnion:
8671 case CK_ArrayToPointerDecay:
8672 case CK_FunctionToPointerDecay:
8673 case CK_NullToPointer:
8674 case CK_NullToMemberPointer:
8675 case CK_BaseToDerivedMemberPointer:
8676 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008677 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008678 case CK_ConstructorConversion:
8679 case CK_IntegralToPointer:
8680 case CK_ToVoid:
8681 case CK_VectorSplat:
8682 case CK_IntegralToFloating:
8683 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008684 case CK_CPointerToObjCPointerCast:
8685 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008686 case CK_AnyPointerToBlockPointerCast:
8687 case CK_ObjCObjectLValueCast:
8688 case CK_FloatingRealToComplex:
8689 case CK_FloatingComplexToReal:
8690 case CK_FloatingComplexCast:
8691 case CK_FloatingComplexToIntegralComplex:
8692 case CK_IntegralRealToComplex:
8693 case CK_IntegralComplexCast:
8694 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008695 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008696 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008697 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008698 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008699 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008700 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008701 llvm_unreachable("invalid cast kind for integral value");
8702
Eli Friedman9faf2f92011-03-25 19:07:11 +00008703 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008704 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008705 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008706 case CK_ARCProduceObject:
8707 case CK_ARCConsumeObject:
8708 case CK_ARCReclaimReturnedObject:
8709 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008710 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008711 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008712
Richard Smith4ef685b2012-01-17 21:17:26 +00008713 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008714 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008715 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008716 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008717 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008718
8719 case CK_MemberPointerToBoolean:
8720 case CK_PointerToBoolean:
8721 case CK_IntegralToBoolean:
8722 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008723 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008724 case CK_FloatingComplexToBoolean:
8725 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008726 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008727 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008728 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008729 uint64_t IntResult = BoolResult;
8730 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8731 IntResult = (uint64_t)-1;
8732 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008733 }
8734
Eli Friedmanc757de22011-03-25 00:43:55 +00008735 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008736 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008737 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008738
Eli Friedman742421e2009-02-20 01:15:07 +00008739 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008740 // Allow casts of address-of-label differences if they are no-ops
8741 // or narrowing. (The narrowing case isn't actually guaranteed to
8742 // be constant-evaluatable except in some narrow cases which are hard
8743 // to detect here. We let it through on the assumption the user knows
8744 // what they are doing.)
8745 if (Result.isAddrLabelDiff())
8746 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008747 // Only allow casts of lvalues if they are lossless.
8748 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8749 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008750
Richard Smith911e1422012-01-30 22:27:01 +00008751 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8752 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008753 }
Mike Stump11289f42009-09-09 15:08:12 +00008754
Eli Friedmanc757de22011-03-25 00:43:55 +00008755 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008756 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8757
John McCall45d55e42010-05-07 21:00:08 +00008758 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008759 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008760 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008761
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008762 if (LV.getLValueBase()) {
8763 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008764 // FIXME: Allow a larger integer size than the pointer size, and allow
8765 // narrowing back down to pointer width in subsequent integral casts.
8766 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008767 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008768 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008769
Richard Smithcf74da72011-11-16 07:18:12 +00008770 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008771 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008772 return true;
8773 }
8774
Yaxun Liu402804b2016-12-15 08:09:08 +00008775 uint64_t V;
8776 if (LV.isNullPointer())
8777 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8778 else
8779 V = LV.getLValueOffset().getQuantity();
8780
8781 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008782 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008783 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008784
Eli Friedmanc757de22011-03-25 00:43:55 +00008785 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008786 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008787 if (!EvaluateComplex(SubExpr, C, Info))
8788 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008789 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008790 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008791
Eli Friedmanc757de22011-03-25 00:43:55 +00008792 case CK_FloatingToIntegral: {
8793 APFloat F(0.0);
8794 if (!EvaluateFloat(SubExpr, F, Info))
8795 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008796
Richard Smith357362d2011-12-13 06:39:58 +00008797 APSInt Value;
8798 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8799 return false;
8800 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008801 }
8802 }
Mike Stump11289f42009-09-09 15:08:12 +00008803
Eli Friedmanc757de22011-03-25 00:43:55 +00008804 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008805}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008806
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008807bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8808 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008809 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008810 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8811 return false;
8812 if (!LV.isComplexInt())
8813 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008814 return Success(LV.getComplexIntReal(), E);
8815 }
8816
8817 return Visit(E->getSubExpr());
8818}
8819
Eli Friedman4e7a2412009-02-27 04:45:43 +00008820bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008821 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008822 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008823 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8824 return false;
8825 if (!LV.isComplexInt())
8826 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008827 return Success(LV.getComplexIntImag(), E);
8828 }
8829
Richard Smith4a678122011-10-24 18:44:57 +00008830 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008831 return Success(0, E);
8832}
8833
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008834bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8835 return Success(E->getPackLength(), E);
8836}
8837
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008838bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8839 return Success(E->getValue(), E);
8840}
8841
Chris Lattner05706e882008-07-11 18:11:29 +00008842//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008843// Float Evaluation
8844//===----------------------------------------------------------------------===//
8845
8846namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008847class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008848 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008849 APFloat &Result;
8850public:
8851 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008852 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008853
Richard Smith2e312c82012-03-03 22:46:17 +00008854 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008855 Result = V.getFloat();
8856 return true;
8857 }
Eli Friedman24c01542008-08-22 00:06:13 +00008858
Richard Smithfddd3842011-12-30 21:15:51 +00008859 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008860 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8861 return true;
8862 }
8863
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008864 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008865
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008866 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008867 bool VisitBinaryOperator(const BinaryOperator *E);
8868 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008869 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008870
John McCallb1fb0d32010-05-07 22:08:54 +00008871 bool VisitUnaryReal(const UnaryOperator *E);
8872 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008873
Richard Smithfddd3842011-12-30 21:15:51 +00008874 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008875};
8876} // end anonymous namespace
8877
8878static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008879 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008880 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008881}
8882
Jay Foad39c79802011-01-12 09:06:06 +00008883static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008884 QualType ResultTy,
8885 const Expr *Arg,
8886 bool SNaN,
8887 llvm::APFloat &Result) {
8888 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8889 if (!S) return false;
8890
8891 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8892
8893 llvm::APInt fill;
8894
8895 // Treat empty strings as if they were zero.
8896 if (S->getString().empty())
8897 fill = llvm::APInt(32, 0);
8898 else if (S->getString().getAsInteger(0, fill))
8899 return false;
8900
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008901 if (Context.getTargetInfo().isNan2008()) {
8902 if (SNaN)
8903 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8904 else
8905 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8906 } else {
8907 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8908 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8909 // a different encoding to what became a standard in 2008, and for pre-
8910 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8911 // sNaN. This is now known as "legacy NaN" encoding.
8912 if (SNaN)
8913 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8914 else
8915 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8916 }
8917
John McCall16291492010-02-28 13:00:19 +00008918 return true;
8919}
8920
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008921bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008922 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008923 default:
8924 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8925
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008926 case Builtin::BI__builtin_huge_val:
8927 case Builtin::BI__builtin_huge_valf:
8928 case Builtin::BI__builtin_huge_vall:
8929 case Builtin::BI__builtin_inf:
8930 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008931 case Builtin::BI__builtin_infl: {
8932 const llvm::fltSemantics &Sem =
8933 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008934 Result = llvm::APFloat::getInf(Sem);
8935 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008936 }
Mike Stump11289f42009-09-09 15:08:12 +00008937
John McCall16291492010-02-28 13:00:19 +00008938 case Builtin::BI__builtin_nans:
8939 case Builtin::BI__builtin_nansf:
8940 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008941 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8942 true, Result))
8943 return Error(E);
8944 return true;
John McCall16291492010-02-28 13:00:19 +00008945
Chris Lattner0b7282e2008-10-06 06:31:58 +00008946 case Builtin::BI__builtin_nan:
8947 case Builtin::BI__builtin_nanf:
8948 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008949 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008950 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008951 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8952 false, Result))
8953 return Error(E);
8954 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008955
8956 case Builtin::BI__builtin_fabs:
8957 case Builtin::BI__builtin_fabsf:
8958 case Builtin::BI__builtin_fabsl:
8959 if (!EvaluateFloat(E->getArg(0), Result, Info))
8960 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008961
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008962 if (Result.isNegative())
8963 Result.changeSign();
8964 return true;
8965
Richard Smith8889a3d2013-06-13 06:26:32 +00008966 // FIXME: Builtin::BI__builtin_powi
8967 // FIXME: Builtin::BI__builtin_powif
8968 // FIXME: Builtin::BI__builtin_powil
8969
Mike Stump11289f42009-09-09 15:08:12 +00008970 case Builtin::BI__builtin_copysign:
8971 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008972 case Builtin::BI__builtin_copysignl: {
8973 APFloat RHS(0.);
8974 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8975 !EvaluateFloat(E->getArg(1), RHS, Info))
8976 return false;
8977 Result.copySign(RHS);
8978 return true;
8979 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008980 }
8981}
8982
John McCallb1fb0d32010-05-07 22:08:54 +00008983bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008984 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8985 ComplexValue CV;
8986 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8987 return false;
8988 Result = CV.FloatReal;
8989 return true;
8990 }
8991
8992 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00008993}
8994
8995bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008996 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8997 ComplexValue CV;
8998 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8999 return false;
9000 Result = CV.FloatImag;
9001 return true;
9002 }
9003
Richard Smith4a678122011-10-24 18:44:57 +00009004 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009005 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9006 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009007 return true;
9008}
9009
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009010bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009011 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009012 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009013 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009014 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009015 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009016 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9017 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009018 Result.changeSign();
9019 return true;
9020 }
9021}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009022
Eli Friedman24c01542008-08-22 00:06:13 +00009023bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009024 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9025 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009026
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009027 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009028 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009029 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009030 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009031 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9032 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009033}
9034
9035bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9036 Result = E->getValue();
9037 return true;
9038}
9039
Peter Collingbournee9200682011-05-13 03:29:01 +00009040bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9041 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009042
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009043 switch (E->getCastKind()) {
9044 default:
Richard Smith11562c52011-10-28 17:51:58 +00009045 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009046
9047 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009048 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009049 return EvaluateInteger(SubExpr, IntResult, Info) &&
9050 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9051 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009052 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009053
9054 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009055 if (!Visit(SubExpr))
9056 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009057 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9058 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009059 }
John McCalld7646252010-11-14 08:17:51 +00009060
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009061 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009062 ComplexValue V;
9063 if (!EvaluateComplex(SubExpr, V, Info))
9064 return false;
9065 Result = V.getComplexFloatReal();
9066 return true;
9067 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009068 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009069}
9070
Eli Friedman24c01542008-08-22 00:06:13 +00009071//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009072// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009073//===----------------------------------------------------------------------===//
9074
9075namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009076class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009077 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009078 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009079
Anders Carlsson537969c2008-11-16 20:27:53 +00009080public:
John McCall93d91dc2010-05-07 17:22:02 +00009081 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009082 : ExprEvaluatorBaseTy(info), Result(Result) {}
9083
Richard Smith2e312c82012-03-03 22:46:17 +00009084 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009085 Result.setFrom(V);
9086 return true;
9087 }
Mike Stump11289f42009-09-09 15:08:12 +00009088
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009089 bool ZeroInitialization(const Expr *E);
9090
Anders Carlsson537969c2008-11-16 20:27:53 +00009091 //===--------------------------------------------------------------------===//
9092 // Visitor Methods
9093 //===--------------------------------------------------------------------===//
9094
Peter Collingbournee9200682011-05-13 03:29:01 +00009095 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009096 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009097 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009098 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009099 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009100};
9101} // end anonymous namespace
9102
John McCall93d91dc2010-05-07 17:22:02 +00009103static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9104 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009105 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009106 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009107}
9108
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009109bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009110 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009111 if (ElemTy->isRealFloatingType()) {
9112 Result.makeComplexFloat();
9113 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9114 Result.FloatReal = Zero;
9115 Result.FloatImag = Zero;
9116 } else {
9117 Result.makeComplexInt();
9118 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9119 Result.IntReal = Zero;
9120 Result.IntImag = Zero;
9121 }
9122 return true;
9123}
9124
Peter Collingbournee9200682011-05-13 03:29:01 +00009125bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9126 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009127
9128 if (SubExpr->getType()->isRealFloatingType()) {
9129 Result.makeComplexFloat();
9130 APFloat &Imag = Result.FloatImag;
9131 if (!EvaluateFloat(SubExpr, Imag, Info))
9132 return false;
9133
9134 Result.FloatReal = APFloat(Imag.getSemantics());
9135 return true;
9136 } else {
9137 assert(SubExpr->getType()->isIntegerType() &&
9138 "Unexpected imaginary literal.");
9139
9140 Result.makeComplexInt();
9141 APSInt &Imag = Result.IntImag;
9142 if (!EvaluateInteger(SubExpr, Imag, Info))
9143 return false;
9144
9145 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9146 return true;
9147 }
9148}
9149
Peter Collingbournee9200682011-05-13 03:29:01 +00009150bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009151
John McCallfcef3cf2010-12-14 17:51:41 +00009152 switch (E->getCastKind()) {
9153 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009154 case CK_BaseToDerived:
9155 case CK_DerivedToBase:
9156 case CK_UncheckedDerivedToBase:
9157 case CK_Dynamic:
9158 case CK_ToUnion:
9159 case CK_ArrayToPointerDecay:
9160 case CK_FunctionToPointerDecay:
9161 case CK_NullToPointer:
9162 case CK_NullToMemberPointer:
9163 case CK_BaseToDerivedMemberPointer:
9164 case CK_DerivedToBaseMemberPointer:
9165 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009166 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009167 case CK_ConstructorConversion:
9168 case CK_IntegralToPointer:
9169 case CK_PointerToIntegral:
9170 case CK_PointerToBoolean:
9171 case CK_ToVoid:
9172 case CK_VectorSplat:
9173 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009174 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009175 case CK_IntegralToBoolean:
9176 case CK_IntegralToFloating:
9177 case CK_FloatingToIntegral:
9178 case CK_FloatingToBoolean:
9179 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009180 case CK_CPointerToObjCPointerCast:
9181 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009182 case CK_AnyPointerToBlockPointerCast:
9183 case CK_ObjCObjectLValueCast:
9184 case CK_FloatingComplexToReal:
9185 case CK_FloatingComplexToBoolean:
9186 case CK_IntegralComplexToReal:
9187 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009188 case CK_ARCProduceObject:
9189 case CK_ARCConsumeObject:
9190 case CK_ARCReclaimReturnedObject:
9191 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009192 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009193 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009194 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009195 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009196 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009197 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009198 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009199 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009200
John McCallfcef3cf2010-12-14 17:51:41 +00009201 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009202 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009203 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009204 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009205
9206 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009207 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009208 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009209 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009210
9211 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009212 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009213 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009214 return false;
9215
John McCallfcef3cf2010-12-14 17:51:41 +00009216 Result.makeComplexFloat();
9217 Result.FloatImag = APFloat(Real.getSemantics());
9218 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009219 }
9220
John McCallfcef3cf2010-12-14 17:51:41 +00009221 case CK_FloatingComplexCast: {
9222 if (!Visit(E->getSubExpr()))
9223 return false;
9224
9225 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9226 QualType From
9227 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9228
Richard Smith357362d2011-12-13 06:39:58 +00009229 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9230 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009231 }
9232
9233 case CK_FloatingComplexToIntegralComplex: {
9234 if (!Visit(E->getSubExpr()))
9235 return false;
9236
9237 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9238 QualType From
9239 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9240 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009241 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9242 To, Result.IntReal) &&
9243 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9244 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009245 }
9246
9247 case CK_IntegralRealToComplex: {
9248 APSInt &Real = Result.IntReal;
9249 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9250 return false;
9251
9252 Result.makeComplexInt();
9253 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9254 return true;
9255 }
9256
9257 case CK_IntegralComplexCast: {
9258 if (!Visit(E->getSubExpr()))
9259 return false;
9260
9261 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9262 QualType From
9263 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9264
Richard Smith911e1422012-01-30 22:27:01 +00009265 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9266 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009267 return true;
9268 }
9269
9270 case CK_IntegralComplexToFloatingComplex: {
9271 if (!Visit(E->getSubExpr()))
9272 return false;
9273
Ted Kremenek28831752012-08-23 20:46:57 +00009274 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009275 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009276 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009277 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009278 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9279 To, Result.FloatReal) &&
9280 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9281 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009282 }
9283 }
9284
9285 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009286}
9287
John McCall93d91dc2010-05-07 17:22:02 +00009288bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009289 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009290 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9291
Chandler Carrutha216cad2014-10-11 00:57:18 +00009292 // Track whether the LHS or RHS is real at the type system level. When this is
9293 // the case we can simplify our evaluation strategy.
9294 bool LHSReal = false, RHSReal = false;
9295
9296 bool LHSOK;
9297 if (E->getLHS()->getType()->isRealFloatingType()) {
9298 LHSReal = true;
9299 APFloat &Real = Result.FloatReal;
9300 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9301 if (LHSOK) {
9302 Result.makeComplexFloat();
9303 Result.FloatImag = APFloat(Real.getSemantics());
9304 }
9305 } else {
9306 LHSOK = Visit(E->getLHS());
9307 }
George Burgess IVa145e252016-05-25 22:38:36 +00009308 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009309 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009310
John McCall93d91dc2010-05-07 17:22:02 +00009311 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009312 if (E->getRHS()->getType()->isRealFloatingType()) {
9313 RHSReal = true;
9314 APFloat &Real = RHS.FloatReal;
9315 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9316 return false;
9317 RHS.makeComplexFloat();
9318 RHS.FloatImag = APFloat(Real.getSemantics());
9319 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009320 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009321
Chandler Carrutha216cad2014-10-11 00:57:18 +00009322 assert(!(LHSReal && RHSReal) &&
9323 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009324 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009325 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009326 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009327 if (Result.isComplexFloat()) {
9328 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9329 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009330 if (LHSReal)
9331 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9332 else if (!RHSReal)
9333 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9334 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009335 } else {
9336 Result.getComplexIntReal() += RHS.getComplexIntReal();
9337 Result.getComplexIntImag() += RHS.getComplexIntImag();
9338 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009339 break;
John McCalle3027922010-08-25 11:45:40 +00009340 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009341 if (Result.isComplexFloat()) {
9342 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9343 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009344 if (LHSReal) {
9345 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9346 Result.getComplexFloatImag().changeSign();
9347 } else if (!RHSReal) {
9348 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9349 APFloat::rmNearestTiesToEven);
9350 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009351 } else {
9352 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9353 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9354 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009355 break;
John McCalle3027922010-08-25 11:45:40 +00009356 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009357 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009358 // This is an implementation of complex multiplication according to the
9359 // constraints laid out in C11 Annex G. The implemantion uses the
9360 // following naming scheme:
9361 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009362 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009363 APFloat &A = LHS.getComplexFloatReal();
9364 APFloat &B = LHS.getComplexFloatImag();
9365 APFloat &C = RHS.getComplexFloatReal();
9366 APFloat &D = RHS.getComplexFloatImag();
9367 APFloat &ResR = Result.getComplexFloatReal();
9368 APFloat &ResI = Result.getComplexFloatImag();
9369 if (LHSReal) {
9370 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9371 ResR = A * C;
9372 ResI = A * D;
9373 } else if (RHSReal) {
9374 ResR = C * A;
9375 ResI = C * B;
9376 } else {
9377 // In the fully general case, we need to handle NaNs and infinities
9378 // robustly.
9379 APFloat AC = A * C;
9380 APFloat BD = B * D;
9381 APFloat AD = A * D;
9382 APFloat BC = B * C;
9383 ResR = AC - BD;
9384 ResI = AD + BC;
9385 if (ResR.isNaN() && ResI.isNaN()) {
9386 bool Recalc = false;
9387 if (A.isInfinity() || B.isInfinity()) {
9388 A = APFloat::copySign(
9389 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9390 B = APFloat::copySign(
9391 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9392 if (C.isNaN())
9393 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9394 if (D.isNaN())
9395 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9396 Recalc = true;
9397 }
9398 if (C.isInfinity() || D.isInfinity()) {
9399 C = APFloat::copySign(
9400 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9401 D = APFloat::copySign(
9402 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9403 if (A.isNaN())
9404 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9405 if (B.isNaN())
9406 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9407 Recalc = true;
9408 }
9409 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9410 AD.isInfinity() || BC.isInfinity())) {
9411 if (A.isNaN())
9412 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9413 if (B.isNaN())
9414 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9415 if (C.isNaN())
9416 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9417 if (D.isNaN())
9418 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9419 Recalc = true;
9420 }
9421 if (Recalc) {
9422 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9423 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9424 }
9425 }
9426 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009427 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009428 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009429 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009430 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9431 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009432 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009433 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9434 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9435 }
9436 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009437 case BO_Div:
9438 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009439 // This is an implementation of complex division according to the
9440 // constraints laid out in C11 Annex G. The implemantion uses the
9441 // following naming scheme:
9442 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009443 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009444 APFloat &A = LHS.getComplexFloatReal();
9445 APFloat &B = LHS.getComplexFloatImag();
9446 APFloat &C = RHS.getComplexFloatReal();
9447 APFloat &D = RHS.getComplexFloatImag();
9448 APFloat &ResR = Result.getComplexFloatReal();
9449 APFloat &ResI = Result.getComplexFloatImag();
9450 if (RHSReal) {
9451 ResR = A / C;
9452 ResI = B / C;
9453 } else {
9454 if (LHSReal) {
9455 // No real optimizations we can do here, stub out with zero.
9456 B = APFloat::getZero(A.getSemantics());
9457 }
9458 int DenomLogB = 0;
9459 APFloat MaxCD = maxnum(abs(C), abs(D));
9460 if (MaxCD.isFinite()) {
9461 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009462 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9463 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009464 }
9465 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009466 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9467 APFloat::rmNearestTiesToEven);
9468 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9469 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009470 if (ResR.isNaN() && ResI.isNaN()) {
9471 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9472 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9473 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9474 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9475 D.isFinite()) {
9476 A = APFloat::copySign(
9477 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9478 B = APFloat::copySign(
9479 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9480 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9481 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9482 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9483 C = APFloat::copySign(
9484 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9485 D = APFloat::copySign(
9486 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9487 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9488 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9489 }
9490 }
9491 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009492 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009493 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9494 return Error(E, diag::note_expr_divide_by_zero);
9495
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009496 ComplexValue LHS = Result;
9497 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9498 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9499 Result.getComplexIntReal() =
9500 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9501 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9502 Result.getComplexIntImag() =
9503 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9504 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9505 }
9506 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009507 }
9508
John McCall93d91dc2010-05-07 17:22:02 +00009509 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009510}
9511
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009512bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9513 // Get the operand value into 'Result'.
9514 if (!Visit(E->getSubExpr()))
9515 return false;
9516
9517 switch (E->getOpcode()) {
9518 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009519 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009520 case UO_Extension:
9521 return true;
9522 case UO_Plus:
9523 // The result is always just the subexpr.
9524 return true;
9525 case UO_Minus:
9526 if (Result.isComplexFloat()) {
9527 Result.getComplexFloatReal().changeSign();
9528 Result.getComplexFloatImag().changeSign();
9529 }
9530 else {
9531 Result.getComplexIntReal() = -Result.getComplexIntReal();
9532 Result.getComplexIntImag() = -Result.getComplexIntImag();
9533 }
9534 return true;
9535 case UO_Not:
9536 if (Result.isComplexFloat())
9537 Result.getComplexFloatImag().changeSign();
9538 else
9539 Result.getComplexIntImag() = -Result.getComplexIntImag();
9540 return true;
9541 }
9542}
9543
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009544bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9545 if (E->getNumInits() == 2) {
9546 if (E->getType()->isComplexType()) {
9547 Result.makeComplexFloat();
9548 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9549 return false;
9550 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9551 return false;
9552 } else {
9553 Result.makeComplexInt();
9554 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9555 return false;
9556 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9557 return false;
9558 }
9559 return true;
9560 }
9561 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9562}
9563
Anders Carlsson537969c2008-11-16 20:27:53 +00009564//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009565// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9566// implicit conversion.
9567//===----------------------------------------------------------------------===//
9568
9569namespace {
9570class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009571 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00009572 APValue &Result;
9573public:
9574 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
9575 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9576
9577 bool Success(const APValue &V, const Expr *E) {
9578 Result = V;
9579 return true;
9580 }
9581
9582 bool ZeroInitialization(const Expr *E) {
9583 ImplicitValueInitExpr VIE(
9584 E->getType()->castAs<AtomicType>()->getValueType());
9585 return Evaluate(Result, Info, &VIE);
9586 }
9587
9588 bool VisitCastExpr(const CastExpr *E) {
9589 switch (E->getCastKind()) {
9590 default:
9591 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9592 case CK_NonAtomicToAtomic:
9593 return Evaluate(Result, Info, E->getSubExpr());
9594 }
9595 }
9596};
9597} // end anonymous namespace
9598
9599static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
9600 assert(E->isRValue() && E->getType()->isAtomicType());
9601 return AtomicExprEvaluator(Info, Result).Visit(E);
9602}
9603
9604//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009605// Void expression evaluation, primarily for a cast to void on the LHS of a
9606// comma operator
9607//===----------------------------------------------------------------------===//
9608
9609namespace {
9610class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009611 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009612public:
9613 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9614
Richard Smith2e312c82012-03-03 22:46:17 +00009615 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009616
9617 bool VisitCastExpr(const CastExpr *E) {
9618 switch (E->getCastKind()) {
9619 default:
9620 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9621 case CK_ToVoid:
9622 VisitIgnoredValue(E->getSubExpr());
9623 return true;
9624 }
9625 }
Hal Finkela8443c32014-07-17 14:49:58 +00009626
9627 bool VisitCallExpr(const CallExpr *E) {
9628 switch (E->getBuiltinCallee()) {
9629 default:
9630 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9631 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009632 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009633 // The argument is not evaluated!
9634 return true;
9635 }
9636 }
Richard Smith42d3af92011-12-07 00:43:50 +00009637};
9638} // end anonymous namespace
9639
9640static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9641 assert(E->isRValue() && E->getType()->isVoidType());
9642 return VoidExprEvaluator(Info).Visit(E);
9643}
9644
9645//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009646// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009647//===----------------------------------------------------------------------===//
9648
Richard Smith2e312c82012-03-03 22:46:17 +00009649static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009650 // In C, function designators are not lvalues, but we evaluate them as if they
9651 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009652 QualType T = E->getType();
9653 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009654 LValue LV;
9655 if (!EvaluateLValue(E, LV, Info))
9656 return false;
9657 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009658 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009659 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009660 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009661 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009662 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009663 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009664 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009665 LValue LV;
9666 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009667 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009668 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009669 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009670 llvm::APFloat F(0.0);
9671 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009672 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009673 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009674 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009675 ComplexValue C;
9676 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009677 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009678 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009679 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009680 MemberPtr P;
9681 if (!EvaluateMemberPointer(E, P, Info))
9682 return false;
9683 P.moveInto(Result);
9684 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009685 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009686 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009687 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009688 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9689 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009690 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009691 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009692 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009693 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009694 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009695 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9696 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009697 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009698 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009699 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009700 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009701 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009702 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009703 if (!EvaluateVoid(E, Info))
9704 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009705 } else if (T->isAtomicType()) {
9706 if (!EvaluateAtomic(E, Result, Info))
9707 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009708 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009709 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009710 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009711 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009712 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009713 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009714 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009715
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009716 return true;
9717}
9718
Richard Smithb228a862012-02-15 02:18:13 +00009719/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9720/// cases, the in-place evaluation is essential, since later initializers for
9721/// an object can indirectly refer to subobjects which were initialized earlier.
9722static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009723 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009724 assert(!E->isValueDependent());
9725
Richard Smith7525ff62013-05-09 07:14:00 +00009726 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009727 return false;
9728
9729 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009730 // Evaluate arrays and record types in-place, so that later initializers can
9731 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00009732 if (E->getType()->isArrayType())
9733 return EvaluateArray(E, This, Result, Info);
9734 else if (E->getType()->isRecordType())
9735 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00009736 }
9737
9738 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009739 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009740}
9741
Richard Smithf57d8cb2011-12-09 22:58:01 +00009742/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9743/// lvalue-to-rvalue cast if it is an lvalue.
9744static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009745 if (E->getType().isNull())
9746 return false;
9747
Richard Smithfddd3842011-12-30 21:15:51 +00009748 if (!CheckLiteralType(Info, E))
9749 return false;
9750
Richard Smith2e312c82012-03-03 22:46:17 +00009751 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009752 return false;
9753
9754 if (E->isGLValue()) {
9755 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009756 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009757 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009758 return false;
9759 }
9760
Richard Smith2e312c82012-03-03 22:46:17 +00009761 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009762 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009763}
Richard Smith11562c52011-10-28 17:51:58 +00009764
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009765static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9766 const ASTContext &Ctx, bool &IsConst) {
9767 // Fast-path evaluations of integer literals, since we sometimes see files
9768 // containing vast quantities of these.
9769 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9770 Result.Val = APValue(APSInt(L->getValue(),
9771 L->getType()->isUnsignedIntegerType()));
9772 IsConst = true;
9773 return true;
9774 }
James Dennett0492ef02014-03-14 17:44:10 +00009775
9776 // This case should be rare, but we need to check it before we check on
9777 // the type below.
9778 if (Exp->getType().isNull()) {
9779 IsConst = false;
9780 return true;
9781 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009782
9783 // FIXME: Evaluating values of large array and record types can cause
9784 // performance problems. Only do so in C++11 for now.
9785 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9786 Exp->getType()->isRecordType()) &&
9787 !Ctx.getLangOpts().CPlusPlus11) {
9788 IsConst = false;
9789 return true;
9790 }
9791 return false;
9792}
9793
9794
Richard Smith7b553f12011-10-29 00:50:52 +00009795/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009796/// any crazy technique (that has nothing to do with language standards) that
9797/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009798/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9799/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009800bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009801 bool IsConst;
9802 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9803 return IsConst;
9804
Richard Smith6d4c6582013-11-05 22:18:15 +00009805 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009806 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009807}
9808
Jay Foad39c79802011-01-12 09:06:06 +00009809bool Expr::EvaluateAsBooleanCondition(bool &Result,
9810 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009811 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009812 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009813 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009814}
9815
Richard Smithce8eca52015-12-08 03:21:47 +00009816static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9817 Expr::SideEffectsKind SEK) {
9818 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9819 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9820}
9821
Richard Smith5fab0c92011-12-28 19:48:30 +00009822bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9823 SideEffectsKind AllowSideEffects) const {
9824 if (!getType()->isIntegralOrEnumerationType())
9825 return false;
9826
Richard Smith11562c52011-10-28 17:51:58 +00009827 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009828 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009829 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009830 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009831
Richard Smith11562c52011-10-28 17:51:58 +00009832 Result = ExprResult.Val.getInt();
9833 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009834}
9835
Richard Trieube234c32016-04-21 21:04:55 +00009836bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9837 SideEffectsKind AllowSideEffects) const {
9838 if (!getType()->isRealFloatingType())
9839 return false;
9840
9841 EvalResult ExprResult;
9842 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9843 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9844 return false;
9845
9846 Result = ExprResult.Val.getFloat();
9847 return true;
9848}
9849
Jay Foad39c79802011-01-12 09:06:06 +00009850bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009851 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009852
John McCall45d55e42010-05-07 21:00:08 +00009853 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009854 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9855 !CheckLValueConstantExpression(Info, getExprLoc(),
9856 Ctx.getLValueReferenceType(getType()), LV))
9857 return false;
9858
Richard Smith2e312c82012-03-03 22:46:17 +00009859 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009860 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009861}
9862
Richard Smithd0b4dd62011-12-19 06:19:21 +00009863bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9864 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009865 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009866 // FIXME: Evaluating initializers for large array and record types can cause
9867 // performance problems. Only do so in C++11 for now.
9868 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009869 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009870 return false;
9871
Richard Smithd0b4dd62011-12-19 06:19:21 +00009872 Expr::EvalStatus EStatus;
9873 EStatus.Diag = &Notes;
9874
Richard Smith0c6124b2015-12-03 01:36:22 +00009875 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9876 ? EvalInfo::EM_ConstantExpression
9877 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009878 InitInfo.setEvaluatingDecl(VD, Value);
9879
9880 LValue LVal;
9881 LVal.set(VD);
9882
Richard Smithfddd3842011-12-30 21:15:51 +00009883 // C++11 [basic.start.init]p2:
9884 // Variables with static storage duration or thread storage duration shall be
9885 // zero-initialized before any other initialization takes place.
9886 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009887 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009888 !VD->getType()->isReferenceType()) {
9889 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009890 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009891 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009892 return false;
9893 }
9894
Richard Smith7525ff62013-05-09 07:14:00 +00009895 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9896 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009897 EStatus.HasSideEffects)
9898 return false;
9899
9900 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9901 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009902}
9903
Richard Smith7b553f12011-10-29 00:50:52 +00009904/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9905/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009906bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009907 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009908 return EvaluateAsRValue(Result, Ctx) &&
9909 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009910}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009911
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009912APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009913 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009914 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009915 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009916 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009917 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009918 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009919 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009920
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009921 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009922}
John McCall864e3962010-05-07 05:32:02 +00009923
Richard Smithe9ff7702013-11-05 22:23:30 +00009924void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009925 bool IsConst;
9926 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009927 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009928 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009929 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9930 }
9931}
9932
Richard Smithe6c01442013-06-05 00:46:14 +00009933bool Expr::EvalResult::isGlobalLValue() const {
9934 assert(Val.isLValue());
9935 return IsGlobalLValue(Val.getLValueBase());
9936}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009937
9938
John McCall864e3962010-05-07 05:32:02 +00009939/// isIntegerConstantExpr - this recursive routine will test if an expression is
9940/// an integer constant expression.
9941
9942/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9943/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009944
9945// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009946// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9947// and a (possibly null) SourceLocation indicating the location of the problem.
9948//
John McCall864e3962010-05-07 05:32:02 +00009949// Note that to reduce code duplication, this helper does no evaluation
9950// itself; the caller checks whether the expression is evaluatable, and
9951// in the rare cases where CheckICE actually cares about the evaluated
9952// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00009953
Dan Gohman28ade552010-07-26 21:25:24 +00009954namespace {
9955
Richard Smith9e575da2012-12-28 13:25:52 +00009956enum ICEKind {
9957 /// This expression is an ICE.
9958 IK_ICE,
9959 /// This expression is not an ICE, but if it isn't evaluated, it's
9960 /// a legal subexpression for an ICE. This return value is used to handle
9961 /// the comma operator in C99 mode, and non-constant subexpressions.
9962 IK_ICEIfUnevaluated,
9963 /// This expression is not an ICE, and is not a legal subexpression for one.
9964 IK_NotICE
9965};
9966
John McCall864e3962010-05-07 05:32:02 +00009967struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009968 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009969 SourceLocation Loc;
9970
Richard Smith9e575da2012-12-28 13:25:52 +00009971 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009972};
9973
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009974}
Dan Gohman28ade552010-07-26 21:25:24 +00009975
Richard Smith9e575da2012-12-28 13:25:52 +00009976static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9977
9978static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00009979
Craig Toppera31a8822013-08-22 07:09:37 +00009980static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009981 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00009982 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00009983 !EVResult.Val.isInt())
9984 return ICEDiag(IK_NotICE, E->getLocStart());
9985
John McCall864e3962010-05-07 05:32:02 +00009986 return NoDiag();
9987}
9988
Craig Toppera31a8822013-08-22 07:09:37 +00009989static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009990 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00009991 if (!E->getType()->isIntegralOrEnumerationType())
9992 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009993
9994 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00009995#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00009996#define STMT(Node, Base) case Expr::Node##Class:
9997#define EXPR(Node, Base)
9998#include "clang/AST/StmtNodes.inc"
9999 case Expr::PredefinedExprClass:
10000 case Expr::FloatingLiteralClass:
10001 case Expr::ImaginaryLiteralClass:
10002 case Expr::StringLiteralClass:
10003 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010004 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010005 case Expr::MemberExprClass:
10006 case Expr::CompoundAssignOperatorClass:
10007 case Expr::CompoundLiteralExprClass:
10008 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010009 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010010 case Expr::ArrayInitLoopExprClass:
10011 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010012 case Expr::NoInitExprClass:
10013 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010014 case Expr::ImplicitValueInitExprClass:
10015 case Expr::ParenListExprClass:
10016 case Expr::VAArgExprClass:
10017 case Expr::AddrLabelExprClass:
10018 case Expr::StmtExprClass:
10019 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010020 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010021 case Expr::CXXDynamicCastExprClass:
10022 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010023 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010024 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010025 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010026 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010027 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010028 case Expr::CXXThisExprClass:
10029 case Expr::CXXThrowExprClass:
10030 case Expr::CXXNewExprClass:
10031 case Expr::CXXDeleteExprClass:
10032 case Expr::CXXPseudoDestructorExprClass:
10033 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010034 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010035 case Expr::DependentScopeDeclRefExprClass:
10036 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010037 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010038 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010039 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010040 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010041 case Expr::CXXTemporaryObjectExprClass:
10042 case Expr::CXXUnresolvedConstructExprClass:
10043 case Expr::CXXDependentScopeMemberExprClass:
10044 case Expr::UnresolvedMemberExprClass:
10045 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010046 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010047 case Expr::ObjCArrayLiteralClass:
10048 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010049 case Expr::ObjCEncodeExprClass:
10050 case Expr::ObjCMessageExprClass:
10051 case Expr::ObjCSelectorExprClass:
10052 case Expr::ObjCProtocolExprClass:
10053 case Expr::ObjCIvarRefExprClass:
10054 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010055 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010056 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010057 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010058 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010059 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010060 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010061 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010062 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010063 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010064 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010065 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010066 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010067 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010068 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010069 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010070 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010071 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010072 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010073 case Expr::CoawaitExprClass:
10074 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010075 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010076
Richard Smithf137f932014-01-25 20:50:08 +000010077 case Expr::InitListExprClass: {
10078 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10079 // form "T x = { a };" is equivalent to "T x = a;".
10080 // Unless we're initializing a reference, T is a scalar as it is known to be
10081 // of integral or enumeration type.
10082 if (E->isRValue())
10083 if (cast<InitListExpr>(E)->getNumInits() == 1)
10084 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10085 return ICEDiag(IK_NotICE, E->getLocStart());
10086 }
10087
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010088 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010089 case Expr::GNUNullExprClass:
10090 // GCC considers the GNU __null value to be an integral constant expression.
10091 return NoDiag();
10092
John McCall7c454bb2011-07-15 05:09:51 +000010093 case Expr::SubstNonTypeTemplateParmExprClass:
10094 return
10095 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10096
John McCall864e3962010-05-07 05:32:02 +000010097 case Expr::ParenExprClass:
10098 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010099 case Expr::GenericSelectionExprClass:
10100 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010101 case Expr::IntegerLiteralClass:
10102 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010103 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010104 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010105 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010106 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010107 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010108 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010109 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010110 return NoDiag();
10111 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010112 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010113 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10114 // constant expressions, but they can never be ICEs because an ICE cannot
10115 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010116 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010117 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010118 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010119 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010120 }
Richard Smith6365c912012-02-24 22:12:32 +000010121 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010122 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10123 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010124 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010125 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010126 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010127 // Parameter variables are never constants. Without this check,
10128 // getAnyInitializer() can find a default argument, which leads
10129 // to chaos.
10130 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010131 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010132
10133 // C++ 7.1.5.1p2
10134 // A variable of non-volatile const-qualified integral or enumeration
10135 // type initialized by an ICE can be used in ICEs.
10136 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010137 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010138 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010139
Richard Smithd0b4dd62011-12-19 06:19:21 +000010140 const VarDecl *VD;
10141 // Look for a declaration of this variable that has an initializer, and
10142 // check whether it is an ICE.
10143 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10144 return NoDiag();
10145 else
Richard Smith9e575da2012-12-28 13:25:52 +000010146 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010147 }
10148 }
Richard Smith9e575da2012-12-28 13:25:52 +000010149 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010150 }
John McCall864e3962010-05-07 05:32:02 +000010151 case Expr::UnaryOperatorClass: {
10152 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10153 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010154 case UO_PostInc:
10155 case UO_PostDec:
10156 case UO_PreInc:
10157 case UO_PreDec:
10158 case UO_AddrOf:
10159 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010160 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010161 // C99 6.6/3 allows increment and decrement within unevaluated
10162 // subexpressions of constant expressions, but they can never be ICEs
10163 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010164 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010165 case UO_Extension:
10166 case UO_LNot:
10167 case UO_Plus:
10168 case UO_Minus:
10169 case UO_Not:
10170 case UO_Real:
10171 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010172 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010173 }
Richard Smith9e575da2012-12-28 13:25:52 +000010174
John McCall864e3962010-05-07 05:32:02 +000010175 // OffsetOf falls through here.
10176 }
10177 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010178 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10179 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10180 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10181 // compliance: we should warn earlier for offsetof expressions with
10182 // array subscripts that aren't ICEs, and if the array subscripts
10183 // are ICEs, the value of the offsetof must be an integer constant.
10184 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010185 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010186 case Expr::UnaryExprOrTypeTraitExprClass: {
10187 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10188 if ((Exp->getKind() == UETT_SizeOf) &&
10189 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010190 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010191 return NoDiag();
10192 }
10193 case Expr::BinaryOperatorClass: {
10194 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10195 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010196 case BO_PtrMemD:
10197 case BO_PtrMemI:
10198 case BO_Assign:
10199 case BO_MulAssign:
10200 case BO_DivAssign:
10201 case BO_RemAssign:
10202 case BO_AddAssign:
10203 case BO_SubAssign:
10204 case BO_ShlAssign:
10205 case BO_ShrAssign:
10206 case BO_AndAssign:
10207 case BO_XorAssign:
10208 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000010209 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10210 // constant expressions, but they can never be ICEs because an ICE cannot
10211 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010212 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010213
John McCalle3027922010-08-25 11:45:40 +000010214 case BO_Mul:
10215 case BO_Div:
10216 case BO_Rem:
10217 case BO_Add:
10218 case BO_Sub:
10219 case BO_Shl:
10220 case BO_Shr:
10221 case BO_LT:
10222 case BO_GT:
10223 case BO_LE:
10224 case BO_GE:
10225 case BO_EQ:
10226 case BO_NE:
10227 case BO_And:
10228 case BO_Xor:
10229 case BO_Or:
10230 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010231 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10232 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010233 if (Exp->getOpcode() == BO_Div ||
10234 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010235 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010236 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010237 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010238 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010239 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010240 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010241 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010242 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010243 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010244 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010245 }
10246 }
10247 }
John McCalle3027922010-08-25 11:45:40 +000010248 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010249 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010250 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10251 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010252 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10253 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010254 } else {
10255 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010256 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010257 }
10258 }
Richard Smith9e575da2012-12-28 13:25:52 +000010259 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010260 }
John McCalle3027922010-08-25 11:45:40 +000010261 case BO_LAnd:
10262 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010263 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10264 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010265 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010266 // Rare case where the RHS has a comma "side-effect"; we need
10267 // to actually check the condition to see whether the side
10268 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010269 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010270 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010271 return RHSResult;
10272 return NoDiag();
10273 }
10274
Richard Smith9e575da2012-12-28 13:25:52 +000010275 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010276 }
10277 }
10278 }
10279 case Expr::ImplicitCastExprClass:
10280 case Expr::CStyleCastExprClass:
10281 case Expr::CXXFunctionalCastExprClass:
10282 case Expr::CXXStaticCastExprClass:
10283 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010284 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010285 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010286 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010287 if (isa<ExplicitCastExpr>(E)) {
10288 if (const FloatingLiteral *FL
10289 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10290 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10291 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10292 APSInt IgnoredVal(DestWidth, !DestSigned);
10293 bool Ignored;
10294 // If the value does not fit in the destination type, the behavior is
10295 // undefined, so we are not required to treat it as a constant
10296 // expression.
10297 if (FL->getValue().convertToInteger(IgnoredVal,
10298 llvm::APFloat::rmTowardZero,
10299 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010300 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010301 return NoDiag();
10302 }
10303 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010304 switch (cast<CastExpr>(E)->getCastKind()) {
10305 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010306 case CK_AtomicToNonAtomic:
10307 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010308 case CK_NoOp:
10309 case CK_IntegralToBoolean:
10310 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010311 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010312 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010313 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010314 }
John McCall864e3962010-05-07 05:32:02 +000010315 }
John McCallc07a0c72011-02-17 10:25:35 +000010316 case Expr::BinaryConditionalOperatorClass: {
10317 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10318 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010319 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010320 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010321 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10322 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10323 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010324 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010325 return FalseResult;
10326 }
John McCall864e3962010-05-07 05:32:02 +000010327 case Expr::ConditionalOperatorClass: {
10328 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10329 // If the condition (ignoring parens) is a __builtin_constant_p call,
10330 // then only the true side is actually considered in an integer constant
10331 // expression, and it is fully evaluated. This is an important GNU
10332 // extension. See GCC PR38377 for discussion.
10333 if (const CallExpr *CallCE
10334 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010335 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010336 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010337 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010338 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010339 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010340
Richard Smithf57d8cb2011-12-09 22:58:01 +000010341 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10342 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010343
Richard Smith9e575da2012-12-28 13:25:52 +000010344 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010345 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010346 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010347 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010348 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010349 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010350 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010351 return NoDiag();
10352 // Rare case where the diagnostics depend on which side is evaluated
10353 // Note that if we get here, CondResult is 0, and at least one of
10354 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010355 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010356 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010357 return TrueResult;
10358 }
10359 case Expr::CXXDefaultArgExprClass:
10360 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010361 case Expr::CXXDefaultInitExprClass:
10362 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010363 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010364 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010365 }
10366 }
10367
David Blaikiee4d798f2012-01-20 21:50:17 +000010368 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010369}
10370
Richard Smithf57d8cb2011-12-09 22:58:01 +000010371/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010372static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010373 const Expr *E,
10374 llvm::APSInt *Value,
10375 SourceLocation *Loc) {
10376 if (!E->getType()->isIntegralOrEnumerationType()) {
10377 if (Loc) *Loc = E->getExprLoc();
10378 return false;
10379 }
10380
Richard Smith66e05fe2012-01-18 05:21:49 +000010381 APValue Result;
10382 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010383 return false;
10384
Richard Smith98710fc2014-11-13 23:03:19 +000010385 if (!Result.isInt()) {
10386 if (Loc) *Loc = E->getExprLoc();
10387 return false;
10388 }
10389
Richard Smith66e05fe2012-01-18 05:21:49 +000010390 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010391 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010392}
10393
Craig Toppera31a8822013-08-22 07:09:37 +000010394bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10395 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010396 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010397 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010398
Richard Smith9e575da2012-12-28 13:25:52 +000010399 ICEDiag D = CheckICE(this, Ctx);
10400 if (D.Kind != IK_ICE) {
10401 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010402 return false;
10403 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010404 return true;
10405}
10406
Craig Toppera31a8822013-08-22 07:09:37 +000010407bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010408 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010409 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010410 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10411
10412 if (!isIntegerConstantExpr(Ctx, Loc))
10413 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010414 // The only possible side-effects here are due to UB discovered in the
10415 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10416 // required to treat the expression as an ICE, so we produce the folded
10417 // value.
10418 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010419 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010420 return true;
10421}
Richard Smith66e05fe2012-01-18 05:21:49 +000010422
Craig Toppera31a8822013-08-22 07:09:37 +000010423bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010424 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010425}
10426
Craig Toppera31a8822013-08-22 07:09:37 +000010427bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010428 SourceLocation *Loc) const {
10429 // We support this checking in C++98 mode in order to diagnose compatibility
10430 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010431 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010432
Richard Smith98a0a492012-02-14 21:38:30 +000010433 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010434 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010435 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010436 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010437 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010438
10439 APValue Scratch;
10440 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10441
10442 if (!Diags.empty()) {
10443 IsConstExpr = false;
10444 if (Loc) *Loc = Diags[0].first;
10445 } else if (!IsConstExpr) {
10446 // FIXME: This shouldn't happen.
10447 if (Loc) *Loc = getExprLoc();
10448 }
10449
10450 return IsConstExpr;
10451}
Richard Smith253c2a32012-01-27 01:14:48 +000010452
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010453bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10454 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010455 ArrayRef<const Expr*> Args,
10456 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010457 Expr::EvalStatus Status;
10458 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10459
George Burgess IV177399e2017-01-09 04:12:14 +000010460 LValue ThisVal;
10461 const LValue *ThisPtr = nullptr;
10462 if (This) {
10463#ifndef NDEBUG
10464 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10465 assert(MD && "Don't provide `this` for non-methods.");
10466 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10467#endif
10468 if (EvaluateObjectArgument(Info, This, ThisVal))
10469 ThisPtr = &ThisVal;
10470 if (Info.EvalStatus.HasSideEffects)
10471 return false;
10472 }
10473
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010474 ArgVector ArgValues(Args.size());
10475 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10476 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010477 if ((*I)->isValueDependent() ||
10478 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010479 // If evaluation fails, throw away the argument entirely.
10480 ArgValues[I - Args.begin()] = APValue();
10481 if (Info.EvalStatus.HasSideEffects)
10482 return false;
10483 }
10484
10485 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010486 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010487 ArgValues.data());
10488 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10489}
10490
Richard Smith253c2a32012-01-27 01:14:48 +000010491bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010492 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010493 PartialDiagnosticAt> &Diags) {
10494 // FIXME: It would be useful to check constexpr function templates, but at the
10495 // moment the constant expression evaluator cannot cope with the non-rigorous
10496 // ASTs which we build for dependent expressions.
10497 if (FD->isDependentContext())
10498 return true;
10499
10500 Expr::EvalStatus Status;
10501 Status.Diag = &Diags;
10502
Richard Smith6d4c6582013-11-05 22:18:15 +000010503 EvalInfo Info(FD->getASTContext(), Status,
10504 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010505
10506 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010507 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010508
Richard Smith7525ff62013-05-09 07:14:00 +000010509 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010510 // is a temporary being used as the 'this' pointer.
10511 LValue This;
10512 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010513 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010514
Richard Smith253c2a32012-01-27 01:14:48 +000010515 ArrayRef<const Expr*> Args;
10516
Richard Smith2e312c82012-03-03 22:46:17 +000010517 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010518 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10519 // Evaluate the call as a constant initializer, to allow the construction
10520 // of objects of non-literal types.
10521 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010522 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10523 } else {
10524 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010525 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010526 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010527 }
Richard Smith253c2a32012-01-27 01:14:48 +000010528
10529 return Diags.empty();
10530}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010531
10532bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10533 const FunctionDecl *FD,
10534 SmallVectorImpl<
10535 PartialDiagnosticAt> &Diags) {
10536 Expr::EvalStatus Status;
10537 Status.Diag = &Diags;
10538
10539 EvalInfo Info(FD->getASTContext(), Status,
10540 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10541
10542 // Fabricate a call stack frame to give the arguments a plausible cover story.
10543 ArrayRef<const Expr*> Args;
10544 ArgVector ArgValues(0);
10545 bool Success = EvaluateArgs(Args, ArgValues, Info);
10546 (void)Success;
10547 assert(Success &&
10548 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010549 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010550
10551 APValue ResultScratch;
10552 Evaluate(ResultScratch, Info, E);
10553 return Diags.empty();
10554}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010555
10556bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10557 unsigned Type) const {
10558 if (!getType()->isPointerType())
10559 return false;
10560
10561 Expr::EvalStatus Status;
10562 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010563 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010564}