blob: 63cd5df94e028fad77cf8278645f437fef1da3b3 [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 IVa7470272016-12-20 01:05:42 +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 IVa7470272016-12-20 01:05:42 +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 IVa7470272016-12-20 01:05:42 +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 IVa7470272016-12-20 01:05:42 +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 IVa7470272016-12-20 01:05:42 +0000203 /// Indicator of whether the first entry is an unsized array.
204 bool 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 IVa7470272016-12-20 01:05:42 +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 IVa7470272016-12-20 01:05:42 +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 IVa7470272016-12-20 01:05:42 +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 IVa7470272016-12-20 01:05:42 +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 IVa7470272016-12-20 01:05:42 +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 IVa7470272016-12-20 01:05:42 +0000262 /// Determine whether the most derived subobject is an array without a
263 /// known bound.
264 bool isMostDerivedAnUnsizedArray() const {
265 return FirstEntryIsAnUnsizedArray && Entries.size() == 1;
266 }
267
268 /// Determine what the most derived array's size is. Results in an assertion
269 /// failure if the most derived array lacks a size.
270 uint64_t getMostDerivedArraySize() const {
271 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
272 return MostDerivedArraySize;
273 }
274
Richard Smitha8105bc2012-01-06 16:39:00 +0000275 /// Determine whether this is a one-past-the-end pointer.
276 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000277 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000278 if (IsOnePastTheEnd)
279 return true;
George Burgess IVa7470272016-12-20 01:05:42 +0000280 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000281 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
282 return true;
283 return false;
284 }
285
286 /// Check that this refers to a valid subobject.
287 bool isValidSubobject() const {
288 if (Invalid)
289 return false;
290 return !isOnePastTheEnd();
291 }
292 /// Check that this refers to a valid subobject, and if not, produce a
293 /// relevant diagnostic and set the designator as invalid.
294 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
295
296 /// Update this designator to refer to the first element within this array.
297 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000298 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000299 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000300 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000301
302 // This is a most-derived object.
303 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000304 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000305 MostDerivedArraySize = CAT->getSize().getZExtValue();
306 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000307 }
George Burgess IVa7470272016-12-20 01:05:42 +0000308 /// Update this designator to refer to the first element within the array of
309 /// elements of type T. This is an array of unknown size.
310 void addUnsizedArrayUnchecked(QualType ElemTy) {
311 PathEntry Entry;
312 Entry.ArrayIndex = 0;
313 Entries.push_back(Entry);
314
315 MostDerivedType = ElemTy;
316 MostDerivedIsArrayElement = true;
317 // The value in MostDerivedArraySize is undefined in this case. So, set it
318 // to an arbitrary value that's likely to loudly break things if it's
319 // used.
320 MostDerivedArraySize = std::numeric_limits<uint64_t>::max() / 2;
321 MostDerivedPathLength = Entries.size();
322 }
Richard Smith96e0c102011-11-04 02:25:55 +0000323 /// Update this designator to refer to the given base or member of this
324 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000325 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000326 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000327 APValue::BaseOrMemberType Value(D, Virtual);
328 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000329 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000330
331 // If this isn't a base class, it's a new most-derived object.
332 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
333 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000334 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000335 MostDerivedArraySize = 0;
336 MostDerivedPathLength = Entries.size();
337 }
Richard Smith96e0c102011-11-04 02:25:55 +0000338 }
Richard Smith66c96992012-02-18 22:04:06 +0000339 /// Update this designator to refer to the given complex component.
340 void addComplexUnchecked(QualType EltTy, bool Imag) {
341 PathEntry Entry;
342 Entry.ArrayIndex = Imag;
343 Entries.push_back(Entry);
344
345 // This is technically a most-derived object, though in practice this
346 // is unlikely to matter.
347 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000348 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000349 MostDerivedArraySize = 2;
350 MostDerivedPathLength = Entries.size();
351 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000352 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000353 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000354 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000355 if (Invalid) return;
George Burgess IVa7470272016-12-20 01:05:42 +0000356 if (isMostDerivedAnUnsizedArray()) {
357 // Can't verify -- trust that the user is doing the right thing (or if
358 // not, trust that the caller will catch the bad behavior).
359 Entries.back().ArrayIndex += N;
360 return;
361 }
George Burgess IVa51c4072015-10-16 01:49:01 +0000362 if (MostDerivedPathLength == Entries.size() &&
363 MostDerivedIsArrayElement) {
Richard Smith80815602011-11-07 05:07:52 +0000364 Entries.back().ArrayIndex += N;
George Burgess IVa7470272016-12-20 01:05:42 +0000365 if (Entries.back().ArrayIndex > getMostDerivedArraySize()) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000366 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
367 setInvalid();
368 }
Richard Smith96e0c102011-11-04 02:25:55 +0000369 return;
370 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000371 // [expr.add]p4: For the purposes of these operators, a pointer to a
372 // nonarray object behaves the same as a pointer to the first element of
373 // an array of length one with the type of the object as its element type.
374 if (IsOnePastTheEnd && N == (uint64_t)-1)
375 IsOnePastTheEnd = false;
376 else if (!IsOnePastTheEnd && N == 1)
377 IsOnePastTheEnd = true;
378 else if (N != 0) {
379 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000380 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000381 }
Richard Smith96e0c102011-11-04 02:25:55 +0000382 }
383 };
384
Richard Smith254a73d2011-10-28 22:34:42 +0000385 /// A stack frame in the constexpr call stack.
386 struct CallStackFrame {
387 EvalInfo &Info;
388
389 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000390 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000391
Richard Smithf6f003a2011-12-16 19:06:07 +0000392 /// Callee - The function which was called.
393 const FunctionDecl *Callee;
394
Richard Smithd62306a2011-11-10 06:34:14 +0000395 /// This - The binding for the this pointer in this call, if any.
396 const LValue *This;
397
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000398 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000399 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000400 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000401
Eli Friedman4830ec82012-06-25 21:21:08 +0000402 // Note that we intentionally use std::map here so that references to
403 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000404 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000405 typedef MapTy::const_iterator temp_iterator;
406 /// Temporaries - Temporary lvalues materialized within this stack frame.
407 MapTy Temporaries;
408
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000409 /// CallLoc - The location of the call expression for this call.
410 SourceLocation CallLoc;
411
412 /// Index - The call index of this call.
413 unsigned Index;
414
Richard Smithf6f003a2011-12-16 19:06:07 +0000415 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
416 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000417 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000418 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000419
420 APValue *getTemporary(const void *Key) {
421 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000422 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000423 }
424 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000425 };
426
Richard Smith852c9db2013-04-20 22:23:05 +0000427 /// Temporarily override 'this'.
428 class ThisOverrideRAII {
429 public:
430 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
431 : Frame(Frame), OldThis(Frame.This) {
432 if (Enable)
433 Frame.This = NewThis;
434 }
435 ~ThisOverrideRAII() {
436 Frame.This = OldThis;
437 }
438 private:
439 CallStackFrame &Frame;
440 const LValue *OldThis;
441 };
442
Richard Smith92b1ce02011-12-12 09:28:41 +0000443 /// A partial diagnostic which we might know in advance that we are not going
444 /// to emit.
445 class OptionalDiagnostic {
446 PartialDiagnostic *Diag;
447
448 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000449 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
450 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000451
452 template<typename T>
453 OptionalDiagnostic &operator<<(const T &v) {
454 if (Diag)
455 *Diag << v;
456 return *this;
457 }
Richard Smithfe800032012-01-31 04:08:20 +0000458
459 OptionalDiagnostic &operator<<(const APSInt &I) {
460 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000461 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000462 I.toString(Buffer);
463 *Diag << StringRef(Buffer.data(), Buffer.size());
464 }
465 return *this;
466 }
467
468 OptionalDiagnostic &operator<<(const APFloat &F) {
469 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000470 // FIXME: Force the precision of the source value down so we don't
471 // print digits which are usually useless (we don't really care here if
472 // we truncate a digit by accident in edge cases). Ideally,
473 // APFloat::toString would automatically print the shortest
474 // representation which rounds to the correct value, but it's a bit
475 // tricky to implement.
476 unsigned precision =
477 llvm::APFloat::semanticsPrecision(F.getSemantics());
478 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000479 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000480 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000481 *Diag << StringRef(Buffer.data(), Buffer.size());
482 }
483 return *this;
484 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000485 };
486
Richard Smith08d6a2c2013-07-24 07:11:57 +0000487 /// A cleanup, and a flag indicating whether it is lifetime-extended.
488 class Cleanup {
489 llvm::PointerIntPair<APValue*, 1, bool> Value;
490
491 public:
492 Cleanup(APValue *Val, bool IsLifetimeExtended)
493 : Value(Val, IsLifetimeExtended) {}
494
495 bool isLifetimeExtended() const { return Value.getInt(); }
496 void endLifetime() {
497 *Value.getPointer() = APValue();
498 }
499 };
500
Richard Smithb228a862012-02-15 02:18:13 +0000501 /// EvalInfo - This is a private struct used by the evaluator to capture
502 /// information about a subexpression as it is folded. It retains information
503 /// about the AST context, but also maintains information about the folded
504 /// expression.
505 ///
506 /// If an expression could be evaluated, it is still possible it is not a C
507 /// "integer constant expression" or constant expression. If not, this struct
508 /// captures information about how and why not.
509 ///
510 /// One bit of information passed *into* the request for constant folding
511 /// indicates whether the subexpression is "evaluated" or not according to C
512 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
513 /// evaluate the expression regardless of what the RHS is, but C only allows
514 /// certain things in certain situations.
Reid Kleckner06df4022016-12-13 19:48:32 +0000515 struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000516 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000517
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000518 /// EvalStatus - Contains information about the evaluation.
519 Expr::EvalStatus &EvalStatus;
520
521 /// CurrentCall - The top of the constexpr call stack.
522 CallStackFrame *CurrentCall;
523
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000524 /// CallStackDepth - The number of calls in the call stack right now.
525 unsigned CallStackDepth;
526
Richard Smithb228a862012-02-15 02:18:13 +0000527 /// NextCallIndex - The next call index to assign.
528 unsigned NextCallIndex;
529
Richard Smitha3d3bd22013-05-08 02:12:03 +0000530 /// StepsLeft - The remaining number of evaluation steps we're permitted
531 /// to perform. This is essentially a limit for the number of statements
532 /// we will evaluate.
533 unsigned StepsLeft;
534
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000535 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000536 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000537 CallStackFrame BottomFrame;
538
Richard Smith08d6a2c2013-07-24 07:11:57 +0000539 /// A stack of values whose lifetimes end at the end of some surrounding
540 /// evaluation frame.
541 llvm::SmallVector<Cleanup, 16> CleanupStack;
542
Richard Smithd62306a2011-11-10 06:34:14 +0000543 /// EvaluatingDecl - This is the declaration whose initializer is being
544 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000545 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000546
547 /// EvaluatingDeclValue - This is the value being constructed for the
548 /// declaration whose initializer is being evaluated, if any.
549 APValue *EvaluatingDeclValue;
550
Richard Smith410306b2016-12-12 02:53:20 +0000551 /// The current array initialization index, if we're performing array
552 /// initialization.
553 uint64_t ArrayInitIndex = -1;
554
Richard Smith357362d2011-12-13 06:39:58 +0000555 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
556 /// notes attached to it will also be stored, otherwise they will not be.
557 bool HasActiveDiagnostic;
558
Richard Smith0c6124b2015-12-03 01:36:22 +0000559 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
560 /// fold (not just why it's not strictly a constant expression)?
561 bool HasFoldFailureDiagnostic;
562
George Burgess IV8c892b52016-05-25 22:31:54 +0000563 /// \brief Whether or not we're currently speculatively evaluating.
564 bool IsSpeculativelyEvaluating;
565
Richard Smith6d4c6582013-11-05 22:18:15 +0000566 enum EvaluationMode {
567 /// Evaluate as a constant expression. Stop if we find that the expression
568 /// is not a constant expression.
569 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000570
Richard Smith6d4c6582013-11-05 22:18:15 +0000571 /// Evaluate as a potential constant expression. Keep going if we hit a
572 /// construct that we can't evaluate yet (because we don't yet know the
573 /// value of something) but stop if we hit something that could never be
574 /// a constant expression.
575 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000576
Richard Smith6d4c6582013-11-05 22:18:15 +0000577 /// Fold the expression to a constant. Stop if we hit a side-effect that
578 /// we can't model.
579 EM_ConstantFold,
580
581 /// Evaluate the expression looking for integer overflow and similar
582 /// issues. Don't worry about side-effects, and try to visit all
583 /// subexpressions.
584 EM_EvaluateForOverflow,
585
586 /// Evaluate in any way we know how. Don't worry about side-effects that
587 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000588 EM_IgnoreSideEffects,
589
590 /// Evaluate as a constant expression. Stop if we find that the expression
591 /// is not a constant expression. Some expressions can be retried in the
592 /// optimizer if we don't constant fold them here, but in an unevaluated
593 /// context we try to fold them immediately since the optimizer never
594 /// gets a chance to look at it.
595 EM_ConstantExpressionUnevaluated,
596
597 /// Evaluate as a potential constant expression. Keep going if we hit a
598 /// construct that we can't evaluate yet (because we don't yet know the
599 /// value of something) but stop if we hit something that could never be
600 /// a constant expression. Some expressions can be retried in the
601 /// optimizer if we don't constant fold them here, but in an unevaluated
602 /// context we try to fold them immediately since the optimizer never
603 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000604 EM_PotentialConstantExpressionUnevaluated,
605
George Burgess IVa7470272016-12-20 01:05:42 +0000606 /// Evaluate as a constant expression. Continue evaluating if either:
607 /// - We find a MemberExpr with a base that can't be evaluated.
608 /// - We find a variable initialized with a call to a function that has
609 /// the alloc_size attribute on it.
610 /// In either case, the LValue returned shall have an invalid base; in the
611 /// former, the base will be the invalid MemberExpr, in the latter, the
612 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
613 /// said CallExpr.
614 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000615 } EvalMode;
616
617 /// Are we checking whether the expression is a potential constant
618 /// expression?
619 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000620 return EvalMode == EM_PotentialConstantExpression ||
621 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000622 }
623
624 /// Are we checking an expression for overflow?
625 // FIXME: We should check for any kind of undefined or suspicious behavior
626 // in such constructs, not just overflow.
627 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
628
629 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000630 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000631 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000632 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000633 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
634 EvaluatingDecl((const ValueDecl *)nullptr),
635 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000636 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
637 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000638
Richard Smith7525ff62013-05-09 07:14:00 +0000639 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
640 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000641 EvaluatingDeclValue = &Value;
642 }
643
David Blaikiebbafb8a2012-03-11 07:00:24 +0000644 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000645
Richard Smith357362d2011-12-13 06:39:58 +0000646 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000647 // Don't perform any constexpr calls (other than the call we're checking)
648 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000649 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000650 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000651 if (NextCallIndex == 0) {
652 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000653 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000654 return false;
655 }
Richard Smith357362d2011-12-13 06:39:58 +0000656 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
657 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000658 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000659 << getLangOpts().ConstexprCallDepth;
660 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000661 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000662
Richard Smithb228a862012-02-15 02:18:13 +0000663 CallStackFrame *getCallFrame(unsigned CallIndex) {
664 assert(CallIndex && "no call index in getCallFrame");
665 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
666 // be null in this loop.
667 CallStackFrame *Frame = CurrentCall;
668 while (Frame->Index > CallIndex)
669 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000670 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000671 }
672
Richard Smitha3d3bd22013-05-08 02:12:03 +0000673 bool nextStep(const Stmt *S) {
674 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000675 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000676 return false;
677 }
678 --StepsLeft;
679 return true;
680 }
681
Richard Smith357362d2011-12-13 06:39:58 +0000682 private:
683 /// Add a diagnostic to the diagnostics list.
684 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
685 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
686 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
687 return EvalStatus.Diag->back().second;
688 }
689
Richard Smithf6f003a2011-12-16 19:06:07 +0000690 /// Add notes containing a call stack to the current point of evaluation.
691 void addCallStack(unsigned Limit);
692
Faisal Valie690b7a2016-07-02 22:34:24 +0000693 private:
694 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
695 unsigned ExtraNotes, bool IsCCEDiag) {
696
Richard Smith92b1ce02011-12-12 09:28:41 +0000697 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000698 // If we have a prior diagnostic, it will be noting that the expression
699 // isn't a constant expression. This diagnostic is more important,
700 // unless we require this evaluation to produce a constant expression.
701 //
702 // FIXME: We might want to show both diagnostics to the user in
703 // EM_ConstantFold mode.
704 if (!EvalStatus.Diag->empty()) {
705 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000706 case EM_ConstantFold:
707 case EM_IgnoreSideEffects:
708 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000709 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000710 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000711 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000712 case EM_ConstantExpression:
713 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000714 case EM_ConstantExpressionUnevaluated:
715 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVa7470272016-12-20 01:05:42 +0000716 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000717 HasActiveDiagnostic = false;
718 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000719 }
720 }
721
Richard Smithf6f003a2011-12-16 19:06:07 +0000722 unsigned CallStackNotes = CallStackDepth - 1;
723 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
724 if (Limit)
725 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000726 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000727 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000728
Richard Smith357362d2011-12-13 06:39:58 +0000729 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000730 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000731 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000732 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
733 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000734 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000735 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000736 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000737 }
Richard Smith357362d2011-12-13 06:39:58 +0000738 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000739 return OptionalDiagnostic();
740 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000741 public:
742 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
743 OptionalDiagnostic
744 FFDiag(SourceLocation Loc,
745 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
746 unsigned ExtraNotes = 0) {
747 return Diag(Loc, DiagId, ExtraNotes, false);
748 }
749
750 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000751 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000752 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000753 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000754 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000755 HasActiveDiagnostic = false;
756 return OptionalDiagnostic();
757 }
758
Richard Smith92b1ce02011-12-12 09:28:41 +0000759 /// Diagnose that the evaluation does not produce a C++11 core constant
760 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000761 ///
762 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
763 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000764 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000765 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000766 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000767 // Don't override a previous diagnostic. Don't bother collecting
768 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000769 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000770 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000771 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000772 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000773 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000774 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000775 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
776 = diag::note_invalid_subexpr_in_const_expr,
777 unsigned ExtraNotes = 0) {
778 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
779 }
Richard Smith357362d2011-12-13 06:39:58 +0000780 /// Add a note to a prior diagnostic.
781 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
782 if (!HasActiveDiagnostic)
783 return OptionalDiagnostic();
784 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000785 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000786
787 /// Add a stack of notes to a prior diagnostic.
788 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
789 if (HasActiveDiagnostic) {
790 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
791 Diags.begin(), Diags.end());
792 }
793 }
Richard Smith253c2a32012-01-27 01:14:48 +0000794
Richard Smith6d4c6582013-11-05 22:18:15 +0000795 /// Should we continue evaluation after encountering a side-effect that we
796 /// couldn't model?
797 bool keepEvaluatingAfterSideEffect() {
798 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000799 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000800 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000801 case EM_EvaluateForOverflow:
802 case EM_IgnoreSideEffects:
803 return true;
804
Richard Smith6d4c6582013-11-05 22:18:15 +0000805 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000806 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000807 case EM_ConstantFold:
George Burgess IVa7470272016-12-20 01:05:42 +0000808 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000809 return false;
810 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000811 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000812 }
813
814 /// Note that we have had a side-effect, and determine whether we should
815 /// keep evaluating.
816 bool noteSideEffect() {
817 EvalStatus.HasSideEffects = true;
818 return keepEvaluatingAfterSideEffect();
819 }
820
Richard Smithce8eca52015-12-08 03:21:47 +0000821 /// Should we continue evaluation after encountering undefined behavior?
822 bool keepEvaluatingAfterUndefinedBehavior() {
823 switch (EvalMode) {
824 case EM_EvaluateForOverflow:
825 case EM_IgnoreSideEffects:
826 case EM_ConstantFold:
George Burgess IVa7470272016-12-20 01:05:42 +0000827 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000828 return true;
829
830 case EM_PotentialConstantExpression:
831 case EM_PotentialConstantExpressionUnevaluated:
832 case EM_ConstantExpression:
833 case EM_ConstantExpressionUnevaluated:
834 return false;
835 }
836 llvm_unreachable("Missed EvalMode case");
837 }
838
839 /// Note that we hit something that was technically undefined behavior, but
840 /// that we can evaluate past it (such as signed overflow or floating-point
841 /// division by zero.)
842 bool noteUndefinedBehavior() {
843 EvalStatus.HasUndefinedBehavior = true;
844 return keepEvaluatingAfterUndefinedBehavior();
845 }
846
Richard Smith253c2a32012-01-27 01:14:48 +0000847 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000848 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000849 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000850 if (!StepsLeft)
851 return false;
852
853 switch (EvalMode) {
854 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000855 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000856 case EM_EvaluateForOverflow:
857 return true;
858
859 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000860 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000861 case EM_ConstantFold:
862 case EM_IgnoreSideEffects:
George Burgess IVa7470272016-12-20 01:05:42 +0000863 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000864 return false;
865 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000866 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000867 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000868
George Burgess IV8c892b52016-05-25 22:31:54 +0000869 /// Notes that we failed to evaluate an expression that other expressions
870 /// directly depend on, and determine if we should keep evaluating. This
871 /// should only be called if we actually intend to keep evaluating.
872 ///
873 /// Call noteSideEffect() instead if we may be able to ignore the value that
874 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
875 ///
876 /// (Foo(), 1) // use noteSideEffect
877 /// (Foo() || true) // use noteSideEffect
878 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000879 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000880 // Failure when evaluating some expression often means there is some
881 // subexpression whose evaluation was skipped. Therefore, (because we
882 // don't track whether we skipped an expression when unwinding after an
883 // evaluation failure) every evaluation failure that bubbles up from a
884 // subexpression implies that a side-effect has potentially happened. We
885 // skip setting the HasSideEffects flag to true until we decide to
886 // continue evaluating after that point, which happens here.
887 bool KeepGoing = keepEvaluatingAfterFailure();
888 EvalStatus.HasSideEffects |= KeepGoing;
889 return KeepGoing;
890 }
891
George Burgess IV3a03fab2015-09-04 21:28:13 +0000892 bool allowInvalidBaseExpr() const {
George Burgess IVa7470272016-12-20 01:05:42 +0000893 return EvalMode == EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000894 }
Richard Smith410306b2016-12-12 02:53:20 +0000895
896 class ArrayInitLoopIndex {
897 EvalInfo &Info;
898 uint64_t OuterIndex;
899
900 public:
901 ArrayInitLoopIndex(EvalInfo &Info)
902 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
903 Info.ArrayInitIndex = 0;
904 }
905 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
906
907 operator uint64_t&() { return Info.ArrayInitIndex; }
908 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000909 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000910
911 /// Object used to treat all foldable expressions as constant expressions.
912 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000913 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000914 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000915 bool HadNoPriorDiags;
916 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000917
Richard Smith6d4c6582013-11-05 22:18:15 +0000918 explicit FoldConstant(EvalInfo &Info, bool Enabled)
919 : Info(Info),
920 Enabled(Enabled),
921 HadNoPriorDiags(Info.EvalStatus.Diag &&
922 Info.EvalStatus.Diag->empty() &&
923 !Info.EvalStatus.HasSideEffects),
924 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000925 if (Enabled &&
926 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
927 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000928 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000929 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000930 void keepDiagnostics() { Enabled = false; }
931 ~FoldConstant() {
932 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000933 !Info.EvalStatus.HasSideEffects)
934 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000935 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000936 }
937 };
Richard Smith17100ba2012-02-16 02:46:34 +0000938
George Burgess IV3a03fab2015-09-04 21:28:13 +0000939 /// RAII object used to treat the current evaluation as the correct pointer
940 /// offset fold for the current EvalMode
941 struct FoldOffsetRAII {
942 EvalInfo &Info;
943 EvalInfo::EvaluationMode OldMode;
George Burgess IVa7470272016-12-20 01:05:42 +0000944 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +0000945 : Info(Info), OldMode(Info.EvalMode) {
946 if (!Info.checkingPotentialConstantExpression())
George Burgess IVa7470272016-12-20 01:05:42 +0000947 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000948 }
949
950 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
951 };
952
George Burgess IV8c892b52016-05-25 22:31:54 +0000953 /// RAII object used to optionally suppress diagnostics and side-effects from
954 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000955 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000956 /// Pair of EvalInfo, and a bit that stores whether or not we were
957 /// speculatively evaluating when we created this RAII.
958 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000959 Expr::EvalStatus Old;
960
George Burgess IV8c892b52016-05-25 22:31:54 +0000961 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
962 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
963 Old = Other.Old;
964 Other.InfoAndOldSpecEval.setPointer(nullptr);
965 }
966
967 void maybeRestoreState() {
968 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
969 if (!Info)
970 return;
971
972 Info->EvalStatus = Old;
973 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
974 }
975
Richard Smith17100ba2012-02-16 02:46:34 +0000976 public:
George Burgess IV8c892b52016-05-25 22:31:54 +0000977 SpeculativeEvaluationRAII() = default;
978
979 SpeculativeEvaluationRAII(
980 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
981 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
982 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +0000983 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +0000984 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000985 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000986
987 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
988 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
989 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +0000990 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000991
992 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
993 maybeRestoreState();
994 moveFromAndCancel(std::move(Other));
995 return *this;
996 }
997
998 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +0000999 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001000
1001 /// RAII object wrapping a full-expression or block scope, and handling
1002 /// the ending of the lifetime of temporaries created within it.
1003 template<bool IsFullExpression>
1004 class ScopeRAII {
1005 EvalInfo &Info;
1006 unsigned OldStackSize;
1007 public:
1008 ScopeRAII(EvalInfo &Info)
1009 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1010 ~ScopeRAII() {
1011 // Body moved to a static method to encourage the compiler to inline away
1012 // instances of this class.
1013 cleanup(Info, OldStackSize);
1014 }
1015 private:
1016 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1017 unsigned NewEnd = OldStackSize;
1018 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1019 I != N; ++I) {
1020 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1021 // Full-expression cleanup of a lifetime-extended temporary: nothing
1022 // to do, just move this cleanup to the right place in the stack.
1023 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1024 ++NewEnd;
1025 } else {
1026 // End the lifetime of the object.
1027 Info.CleanupStack[I].endLifetime();
1028 }
1029 }
1030 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1031 Info.CleanupStack.end());
1032 }
1033 };
1034 typedef ScopeRAII<false> BlockScopeRAII;
1035 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001036}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001037
Richard Smitha8105bc2012-01-06 16:39:00 +00001038bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1039 CheckSubobjectKind CSK) {
1040 if (Invalid)
1041 return false;
1042 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001043 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001044 << CSK;
1045 setInvalid();
1046 return false;
1047 }
1048 return true;
1049}
1050
1051void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1052 const Expr *E, uint64_t N) {
George Burgess IVa7470272016-12-20 01:05:42 +00001053 // If we're complaining, we must be able to statically determine the size of
1054 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001055 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001056 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +00001057 << static_cast<int>(N) << /*array*/ 0
George Burgess IVa7470272016-12-20 01:05:42 +00001058 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001059 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001060 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +00001061 << static_cast<int>(N) << /*non-array*/ 1;
1062 setInvalid();
1063}
1064
Richard Smithf6f003a2011-12-16 19:06:07 +00001065CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1066 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001067 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001068 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1069 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001070 Info.CurrentCall = this;
1071 ++Info.CallStackDepth;
1072}
1073
1074CallStackFrame::~CallStackFrame() {
1075 assert(Info.CurrentCall == this && "calls retired out of order");
1076 --Info.CallStackDepth;
1077 Info.CurrentCall = Caller;
1078}
1079
Richard Smith08d6a2c2013-07-24 07:11:57 +00001080APValue &CallStackFrame::createTemporary(const void *Key,
1081 bool IsLifetimeExtended) {
1082 APValue &Result = Temporaries[Key];
1083 assert(Result.isUninit() && "temporary created multiple times");
1084 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1085 return Result;
1086}
1087
Richard Smith84401042013-06-03 05:03:02 +00001088static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001089
1090void EvalInfo::addCallStack(unsigned Limit) {
1091 // Determine which calls to skip, if any.
1092 unsigned ActiveCalls = CallStackDepth - 1;
1093 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1094 if (Limit && Limit < ActiveCalls) {
1095 SkipStart = Limit / 2 + Limit % 2;
1096 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001097 }
1098
Richard Smithf6f003a2011-12-16 19:06:07 +00001099 // Walk the call stack and add the diagnostics.
1100 unsigned CallIdx = 0;
1101 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1102 Frame = Frame->Caller, ++CallIdx) {
1103 // Skip this call?
1104 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1105 if (CallIdx == SkipStart) {
1106 // Note that we're skipping calls.
1107 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1108 << unsigned(ActiveCalls - Limit);
1109 }
1110 continue;
1111 }
1112
Richard Smith5179eb72016-06-28 19:03:57 +00001113 // Use a different note for an inheriting constructor, because from the
1114 // user's perspective it's not really a function at all.
1115 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1116 if (CD->isInheritingConstructor()) {
1117 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1118 << CD->getParent();
1119 continue;
1120 }
1121 }
1122
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001123 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001124 llvm::raw_svector_ostream Out(Buffer);
1125 describeCall(Frame, Out);
1126 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1127 }
1128}
1129
1130namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001131 struct ComplexValue {
1132 private:
1133 bool IsInt;
1134
1135 public:
1136 APSInt IntReal, IntImag;
1137 APFloat FloatReal, FloatImag;
1138
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001139 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001140
1141 void makeComplexFloat() { IsInt = false; }
1142 bool isComplexFloat() const { return !IsInt; }
1143 APFloat &getComplexFloatReal() { return FloatReal; }
1144 APFloat &getComplexFloatImag() { return FloatImag; }
1145
1146 void makeComplexInt() { IsInt = true; }
1147 bool isComplexInt() const { return IsInt; }
1148 APSInt &getComplexIntReal() { return IntReal; }
1149 APSInt &getComplexIntImag() { return IntImag; }
1150
Richard Smith2e312c82012-03-03 22:46:17 +00001151 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001152 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001153 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001154 else
Richard Smith2e312c82012-03-03 22:46:17 +00001155 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001156 }
Richard Smith2e312c82012-03-03 22:46:17 +00001157 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001158 assert(v.isComplexFloat() || v.isComplexInt());
1159 if (v.isComplexFloat()) {
1160 makeComplexFloat();
1161 FloatReal = v.getComplexFloatReal();
1162 FloatImag = v.getComplexFloatImag();
1163 } else {
1164 makeComplexInt();
1165 IntReal = v.getComplexIntReal();
1166 IntImag = v.getComplexIntImag();
1167 }
1168 }
John McCall93d91dc2010-05-07 17:22:02 +00001169 };
John McCall45d55e42010-05-07 21:00:08 +00001170
1171 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001172 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001173 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001174 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001175 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001176 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001177 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001178
Richard Smithce40ad62011-11-12 22:28:03 +00001179 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001180 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001181 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001182 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001183 SubobjectDesignator &getLValueDesignator() { return Designator; }
1184 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001185 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001186
Richard Smith2e312c82012-03-03 22:46:17 +00001187 void moveInto(APValue &V) const {
1188 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001189 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1190 IsNullPtr);
George Burgess IVa7470272016-12-20 01:05:42 +00001191 else {
1192 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1193 assert(!Designator.FirstEntryIsAnUnsizedArray &&
1194 "Unsized array with a valid base?");
Richard Smith2e312c82012-03-03 22:46:17 +00001195 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001196 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVa7470272016-12-20 01:05:42 +00001197 }
John McCall45d55e42010-05-07 21:00:08 +00001198 }
Richard Smith2e312c82012-03-03 22:46:17 +00001199 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVa7470272016-12-20 01:05:42 +00001200 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001201 Base = V.getLValueBase();
1202 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001203 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001204 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001205 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001206 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001207 }
1208
Yaxun Liu402804b2016-12-15 08:09:08 +00001209 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
1210 bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
George Burgess IVa7470272016-12-20 01:05:42 +00001211#ifndef NDEBUG
1212 // We only allow a few types of invalid bases. Enforce that here.
1213 if (BInvalid) {
1214 const auto *E = B.get<const Expr *>();
1215 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1216 "Unexpected type of invalid base");
1217 }
1218#endif
1219
Richard Smithce40ad62011-11-12 22:28:03 +00001220 Base = B;
Yaxun Liu402804b2016-12-15 08:09:08 +00001221 Offset = CharUnits::fromQuantity(Offset_);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001222 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001223 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001224 Designator = SubobjectDesignator(getType(B));
Yaxun Liu402804b2016-12-15 08:09:08 +00001225 IsNullPtr = IsNullPtr_;
Richard Smitha8105bc2012-01-06 16:39:00 +00001226 }
1227
George Burgess IV3a03fab2015-09-04 21:28:13 +00001228 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1229 set(B, I, true);
1230 }
1231
Richard Smitha8105bc2012-01-06 16:39:00 +00001232 // Check that this LValue is not based on a null pointer. If it is, produce
1233 // a diagnostic and mark the designator as invalid.
1234 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1235 CheckSubobjectKind CSK) {
1236 if (Designator.Invalid)
1237 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001238 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001239 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001240 << CSK;
1241 Designator.setInvalid();
1242 return false;
1243 }
1244 return true;
1245 }
1246
1247 // Check this LValue refers to an object. If not, set the designator to be
1248 // invalid and emit a diagnostic.
1249 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001250 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001251 Designator.checkSubobject(Info, E, CSK);
1252 }
1253
1254 void addDecl(EvalInfo &Info, const Expr *E,
1255 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001256 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1257 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001258 }
George Burgess IVa7470272016-12-20 01:05:42 +00001259 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1260 assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1261 assert(isBaseAnAllocSizeCall(Base) &&
1262 "Only alloc_size bases can have unsized arrays");
1263 Designator.FirstEntryIsAnUnsizedArray = true;
1264 Designator.addUnsizedArrayUnchecked(ElemTy);
1265 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001266 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001267 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1268 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001269 }
Richard Smith66c96992012-02-18 22:04:06 +00001270 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001271 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1272 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001273 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001274 void clearIsNullPointer() {
1275 IsNullPtr = false;
1276 }
1277 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, uint64_t Index,
1278 CharUnits ElementSize) {
1279 // Compute the new offset in the appropriate width.
1280 Offset += Index * ElementSize;
1281 if (Index && checkNullPointer(Info, E, CSK_ArrayIndex))
1282 Designator.adjustIndex(Info, E, Index);
1283 if (Index)
1284 clearIsNullPointer();
1285 }
1286 void adjustOffset(CharUnits N) {
1287 Offset += N;
1288 if (N.getQuantity())
1289 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001290 }
John McCall45d55e42010-05-07 21:00:08 +00001291 };
Richard Smith027bf112011-11-17 22:56:20 +00001292
1293 struct MemberPtr {
1294 MemberPtr() {}
1295 explicit MemberPtr(const ValueDecl *Decl) :
1296 DeclAndIsDerivedMember(Decl, false), Path() {}
1297
1298 /// The member or (direct or indirect) field referred to by this member
1299 /// pointer, or 0 if this is a null member pointer.
1300 const ValueDecl *getDecl() const {
1301 return DeclAndIsDerivedMember.getPointer();
1302 }
1303 /// Is this actually a member of some type derived from the relevant class?
1304 bool isDerivedMember() const {
1305 return DeclAndIsDerivedMember.getInt();
1306 }
1307 /// Get the class which the declaration actually lives in.
1308 const CXXRecordDecl *getContainingRecord() const {
1309 return cast<CXXRecordDecl>(
1310 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1311 }
1312
Richard Smith2e312c82012-03-03 22:46:17 +00001313 void moveInto(APValue &V) const {
1314 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001315 }
Richard Smith2e312c82012-03-03 22:46:17 +00001316 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001317 assert(V.isMemberPointer());
1318 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1319 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1320 Path.clear();
1321 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1322 Path.insert(Path.end(), P.begin(), P.end());
1323 }
1324
1325 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1326 /// whether the member is a member of some class derived from the class type
1327 /// of the member pointer.
1328 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1329 /// Path - The path of base/derived classes from the member declaration's
1330 /// class (exclusive) to the class type of the member pointer (inclusive).
1331 SmallVector<const CXXRecordDecl*, 4> Path;
1332
1333 /// Perform a cast towards the class of the Decl (either up or down the
1334 /// hierarchy).
1335 bool castBack(const CXXRecordDecl *Class) {
1336 assert(!Path.empty());
1337 const CXXRecordDecl *Expected;
1338 if (Path.size() >= 2)
1339 Expected = Path[Path.size() - 2];
1340 else
1341 Expected = getContainingRecord();
1342 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1343 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1344 // if B does not contain the original member and is not a base or
1345 // derived class of the class containing the original member, the result
1346 // of the cast is undefined.
1347 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1348 // (D::*). We consider that to be a language defect.
1349 return false;
1350 }
1351 Path.pop_back();
1352 return true;
1353 }
1354 /// Perform a base-to-derived member pointer cast.
1355 bool castToDerived(const CXXRecordDecl *Derived) {
1356 if (!getDecl())
1357 return true;
1358 if (!isDerivedMember()) {
1359 Path.push_back(Derived);
1360 return true;
1361 }
1362 if (!castBack(Derived))
1363 return false;
1364 if (Path.empty())
1365 DeclAndIsDerivedMember.setInt(false);
1366 return true;
1367 }
1368 /// Perform a derived-to-base member pointer cast.
1369 bool castToBase(const CXXRecordDecl *Base) {
1370 if (!getDecl())
1371 return true;
1372 if (Path.empty())
1373 DeclAndIsDerivedMember.setInt(true);
1374 if (isDerivedMember()) {
1375 Path.push_back(Base);
1376 return true;
1377 }
1378 return castBack(Base);
1379 }
1380 };
Richard Smith357362d2011-12-13 06:39:58 +00001381
Richard Smith7bb00672012-02-01 01:42:44 +00001382 /// Compare two member pointers, which are assumed to be of the same type.
1383 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1384 if (!LHS.getDecl() || !RHS.getDecl())
1385 return !LHS.getDecl() && !RHS.getDecl();
1386 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1387 return false;
1388 return LHS.Path == RHS.Path;
1389 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001390}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001391
Richard Smith2e312c82012-03-03 22:46:17 +00001392static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001393static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1394 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001395 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001396static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1397static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001398static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1399 EvalInfo &Info);
1400static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001401static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001402static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001403 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001404static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001405static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001406static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001407static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001408
1409//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001410// Misc utilities
1411//===----------------------------------------------------------------------===//
1412
Richard Smith84401042013-06-03 05:03:02 +00001413/// Produce a string describing the given constexpr call.
1414static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1415 unsigned ArgIndex = 0;
1416 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1417 !isa<CXXConstructorDecl>(Frame->Callee) &&
1418 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1419
1420 if (!IsMemberCall)
1421 Out << *Frame->Callee << '(';
1422
1423 if (Frame->This && IsMemberCall) {
1424 APValue Val;
1425 Frame->This->moveInto(Val);
1426 Val.printPretty(Out, Frame->Info.Ctx,
1427 Frame->This->Designator.MostDerivedType);
1428 // FIXME: Add parens around Val if needed.
1429 Out << "->" << *Frame->Callee << '(';
1430 IsMemberCall = false;
1431 }
1432
1433 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1434 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1435 if (ArgIndex > (unsigned)IsMemberCall)
1436 Out << ", ";
1437
1438 const ParmVarDecl *Param = *I;
1439 const APValue &Arg = Frame->Arguments[ArgIndex];
1440 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1441
1442 if (ArgIndex == 0 && IsMemberCall)
1443 Out << "->" << *Frame->Callee << '(';
1444 }
1445
1446 Out << ')';
1447}
1448
Richard Smithd9f663b2013-04-22 15:31:51 +00001449/// Evaluate an expression to see if it had side-effects, and discard its
1450/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001451/// \return \c true if the caller should keep evaluating.
1452static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001453 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001454 if (!Evaluate(Scratch, Info, E))
1455 // We don't need the value, but we might have skipped a side effect here.
1456 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001457 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001458}
1459
Richard Smith861b5b52013-05-07 23:34:45 +00001460/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1461/// return its existing value.
1462static int64_t getExtValue(const APSInt &Value) {
1463 return Value.isSigned() ? Value.getSExtValue()
1464 : static_cast<int64_t>(Value.getZExtValue());
1465}
1466
Richard Smithd62306a2011-11-10 06:34:14 +00001467/// Should this call expression be treated as a string literal?
1468static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001469 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001470 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1471 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1472}
1473
Richard Smithce40ad62011-11-12 22:28:03 +00001474static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001475 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1476 // constant expression of pointer type that evaluates to...
1477
1478 // ... a null pointer value, or a prvalue core constant expression of type
1479 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001480 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001481
Richard Smithce40ad62011-11-12 22:28:03 +00001482 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1483 // ... the address of an object with static storage duration,
1484 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1485 return VD->hasGlobalStorage();
1486 // ... the address of a function,
1487 return isa<FunctionDecl>(D);
1488 }
1489
1490 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001491 switch (E->getStmtClass()) {
1492 default:
1493 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001494 case Expr::CompoundLiteralExprClass: {
1495 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1496 return CLE->isFileScope() && CLE->isLValue();
1497 }
Richard Smithe6c01442013-06-05 00:46:14 +00001498 case Expr::MaterializeTemporaryExprClass:
1499 // A materialized temporary might have been lifetime-extended to static
1500 // storage duration.
1501 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001502 // A string literal has static storage duration.
1503 case Expr::StringLiteralClass:
1504 case Expr::PredefinedExprClass:
1505 case Expr::ObjCStringLiteralClass:
1506 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001507 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001508 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001509 return true;
1510 case Expr::CallExprClass:
1511 return IsStringLiteralCall(cast<CallExpr>(E));
1512 // For GCC compatibility, &&label has static storage duration.
1513 case Expr::AddrLabelExprClass:
1514 return true;
1515 // A Block literal expression may be used as the initialization value for
1516 // Block variables at global or local static scope.
1517 case Expr::BlockExprClass:
1518 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001519 case Expr::ImplicitValueInitExprClass:
1520 // FIXME:
1521 // We can never form an lvalue with an implicit value initialization as its
1522 // base through expression evaluation, so these only appear in one case: the
1523 // implicit variable declaration we invent when checking whether a constexpr
1524 // constructor can produce a constant expression. We must assume that such
1525 // an expression might be a global lvalue.
1526 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001527 }
John McCall95007602010-05-10 23:27:23 +00001528}
1529
Richard Smithb228a862012-02-15 02:18:13 +00001530static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1531 assert(Base && "no location for a null lvalue");
1532 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1533 if (VD)
1534 Info.Note(VD->getLocation(), diag::note_declared_at);
1535 else
Ted Kremenek28831752012-08-23 20:46:57 +00001536 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001537 diag::note_constexpr_temporary_here);
1538}
1539
Richard Smith80815602011-11-07 05:07:52 +00001540/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001541/// value for an address or reference constant expression. Return true if we
1542/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001543static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1544 QualType Type, const LValue &LVal) {
1545 bool IsReferenceType = Type->isReferenceType();
1546
Richard Smith357362d2011-12-13 06:39:58 +00001547 APValue::LValueBase Base = LVal.getLValueBase();
1548 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1549
Richard Smith0dea49e2012-02-18 04:58:18 +00001550 // Check that the object is a global. Note that the fake 'this' object we
1551 // manufacture when checking potential constant expressions is conservatively
1552 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001553 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001554 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001555 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001556 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001557 << IsReferenceType << !Designator.Entries.empty()
1558 << !!VD << VD;
1559 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001560 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001561 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001562 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001563 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001564 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001565 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001566 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001567 LVal.getLValueCallIndex() == 0) &&
1568 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001569
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001570 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1571 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001572 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001573 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001574 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001575
Hans Wennborg82dd8772014-06-25 22:19:48 +00001576 // A dllimport variable never acts like a constant.
1577 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001578 return false;
1579 }
1580 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1581 // __declspec(dllimport) must be handled very carefully:
1582 // We must never initialize an expression with the thunk in C++.
1583 // Doing otherwise would allow the same id-expression to yield
1584 // different addresses for the same function in different translation
1585 // units. However, this means that we must dynamically initialize the
1586 // expression with the contents of the import address table at runtime.
1587 //
1588 // The C language has no notion of ODR; furthermore, it has no notion of
1589 // dynamic initialization. This means that we are permitted to
1590 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001591 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001592 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001593 }
1594 }
1595
Richard Smitha8105bc2012-01-06 16:39:00 +00001596 // Allow address constant expressions to be past-the-end pointers. This is
1597 // an extension: the standard requires them to point to an object.
1598 if (!IsReferenceType)
1599 return true;
1600
1601 // A reference constant expression must refer to an object.
1602 if (!Base) {
1603 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001604 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001605 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001606 }
1607
Richard Smith357362d2011-12-13 06:39:58 +00001608 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001609 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001610 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001611 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001612 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001613 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001614 }
1615
Richard Smith80815602011-11-07 05:07:52 +00001616 return true;
1617}
1618
Richard Smithfddd3842011-12-30 21:15:51 +00001619/// Check that this core constant expression is of literal type, and if not,
1620/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001621static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001622 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001623 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001624 return true;
1625
Richard Smith7525ff62013-05-09 07:14:00 +00001626 // C++1y: A constant initializer for an object o [...] may also invoke
1627 // constexpr constructors for o and its subobjects even if those objects
1628 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001629 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001630 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001631 return true;
1632
Richard Smithfddd3842011-12-30 21:15:51 +00001633 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001634 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001635 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001636 << E->getType();
1637 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001638 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001639 return false;
1640}
1641
Richard Smith0b0a0b62011-10-29 20:57:55 +00001642/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001643/// constant expression. If not, report an appropriate diagnostic. Does not
1644/// check that the expression is of literal type.
1645static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1646 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001647 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001648 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001649 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001650 return false;
1651 }
1652
Richard Smith77be48a2014-07-31 06:31:19 +00001653 // We allow _Atomic(T) to be initialized from anything that T can be
1654 // initialized from.
1655 if (const AtomicType *AT = Type->getAs<AtomicType>())
1656 Type = AT->getValueType();
1657
Richard Smithb228a862012-02-15 02:18:13 +00001658 // Core issue 1454: For a literal constant expression of array or class type,
1659 // each subobject of its value shall have been initialized by a constant
1660 // expression.
1661 if (Value.isArray()) {
1662 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1663 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1664 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1665 Value.getArrayInitializedElt(I)))
1666 return false;
1667 }
1668 if (!Value.hasArrayFiller())
1669 return true;
1670 return CheckConstantExpression(Info, DiagLoc, EltTy,
1671 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001672 }
Richard Smithb228a862012-02-15 02:18:13 +00001673 if (Value.isUnion() && Value.getUnionField()) {
1674 return CheckConstantExpression(Info, DiagLoc,
1675 Value.getUnionField()->getType(),
1676 Value.getUnionValue());
1677 }
1678 if (Value.isStruct()) {
1679 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1680 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1681 unsigned BaseIndex = 0;
1682 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1683 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1684 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1685 Value.getStructBase(BaseIndex)))
1686 return false;
1687 }
1688 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001689 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001690 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1691 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001692 return false;
1693 }
1694 }
1695
1696 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001697 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001698 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001699 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1700 }
1701
1702 // Everything else is fine.
1703 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001704}
1705
Benjamin Kramer8407df72015-03-09 16:47:52 +00001706static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001707 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001708}
1709
1710static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001711 if (Value.CallIndex)
1712 return false;
1713 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1714 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001715}
1716
Richard Smithcecf1842011-11-01 21:06:14 +00001717static bool IsWeakLValue(const LValue &Value) {
1718 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001719 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001720}
1721
David Majnemerb5116032014-12-09 23:32:34 +00001722static bool isZeroSized(const LValue &Value) {
1723 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001724 if (Decl && isa<VarDecl>(Decl)) {
1725 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001726 if (Ty->isArrayType())
1727 return Ty->isIncompleteType() ||
1728 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001729 }
1730 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001731}
1732
Richard Smith2e312c82012-03-03 22:46:17 +00001733static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001734 // A null base expression indicates a null pointer. These are always
1735 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001736 if (!Value.getLValueBase()) {
1737 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001738 return true;
1739 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001740
Richard Smith027bf112011-11-17 22:56:20 +00001741 // We have a non-null base. These are generally known to be true, but if it's
1742 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001743 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001744 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001745 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001746}
1747
Richard Smith2e312c82012-03-03 22:46:17 +00001748static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001749 switch (Val.getKind()) {
1750 case APValue::Uninitialized:
1751 return false;
1752 case APValue::Int:
1753 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001754 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001755 case APValue::Float:
1756 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001757 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001758 case APValue::ComplexInt:
1759 Result = Val.getComplexIntReal().getBoolValue() ||
1760 Val.getComplexIntImag().getBoolValue();
1761 return true;
1762 case APValue::ComplexFloat:
1763 Result = !Val.getComplexFloatReal().isZero() ||
1764 !Val.getComplexFloatImag().isZero();
1765 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001766 case APValue::LValue:
1767 return EvalPointerValueAsBool(Val, Result);
1768 case APValue::MemberPointer:
1769 Result = Val.getMemberPointerDecl();
1770 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001771 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001772 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001773 case APValue::Struct:
1774 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001775 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001776 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001777 }
1778
Richard Smith11562c52011-10-28 17:51:58 +00001779 llvm_unreachable("unknown APValue kind");
1780}
1781
1782static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1783 EvalInfo &Info) {
1784 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001785 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001786 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001787 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001788 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001789}
1790
Richard Smith357362d2011-12-13 06:39:58 +00001791template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001792static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001793 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001794 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001795 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001796 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001797}
1798
1799static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1800 QualType SrcType, const APFloat &Value,
1801 QualType DestType, APSInt &Result) {
1802 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001803 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001804 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001805
Richard Smith357362d2011-12-13 06:39:58 +00001806 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001807 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001808 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1809 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001810 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001811 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001812}
1813
Richard Smith357362d2011-12-13 06:39:58 +00001814static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1815 QualType SrcType, QualType DestType,
1816 APFloat &Result) {
1817 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001818 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001819 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1820 APFloat::rmNearestTiesToEven, &ignored)
1821 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001822 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001823 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001824}
1825
Richard Smith911e1422012-01-30 22:27:01 +00001826static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1827 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001828 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001829 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001830 APSInt Result = Value;
1831 // Figure out if this is a truncate, extend or noop cast.
1832 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001833 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001834 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001835 return Result;
1836}
1837
Richard Smith357362d2011-12-13 06:39:58 +00001838static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1839 QualType SrcType, const APSInt &Value,
1840 QualType DestType, APFloat &Result) {
1841 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1842 if (Result.convertFromAPInt(Value, Value.isSigned(),
1843 APFloat::rmNearestTiesToEven)
1844 & APFloat::opOverflow)
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 Smith49ca8aa2013-08-06 07:09:20 +00001849static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1850 APValue &Value, const FieldDecl *FD) {
1851 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1852
1853 if (!Value.isInt()) {
1854 // Trying to store a pointer-cast-to-integer into a bitfield.
1855 // FIXME: In this case, we should provide the diagnostic for casting
1856 // a pointer to an integer.
1857 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001858 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001859 return false;
1860 }
1861
1862 APSInt &Int = Value.getInt();
1863 unsigned OldBitWidth = Int.getBitWidth();
1864 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1865 if (NewBitWidth < OldBitWidth)
1866 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1867 return true;
1868}
1869
Eli Friedman803acb32011-12-22 03:51:45 +00001870static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1871 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001872 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001873 if (!Evaluate(SVal, Info, E))
1874 return false;
1875 if (SVal.isInt()) {
1876 Res = SVal.getInt();
1877 return true;
1878 }
1879 if (SVal.isFloat()) {
1880 Res = SVal.getFloat().bitcastToAPInt();
1881 return true;
1882 }
1883 if (SVal.isVector()) {
1884 QualType VecTy = E->getType();
1885 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1886 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1887 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1888 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1889 Res = llvm::APInt::getNullValue(VecSize);
1890 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1891 APValue &Elt = SVal.getVectorElt(i);
1892 llvm::APInt EltAsInt;
1893 if (Elt.isInt()) {
1894 EltAsInt = Elt.getInt();
1895 } else if (Elt.isFloat()) {
1896 EltAsInt = Elt.getFloat().bitcastToAPInt();
1897 } else {
1898 // Don't try to handle vectors of anything other than int or float
1899 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001900 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001901 return false;
1902 }
1903 unsigned BaseEltSize = EltAsInt.getBitWidth();
1904 if (BigEndian)
1905 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1906 else
1907 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1908 }
1909 return true;
1910 }
1911 // Give up if the input isn't an int, float, or vector. For example, we
1912 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001913 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001914 return false;
1915}
1916
Richard Smith43e77732013-05-07 04:50:00 +00001917/// Perform the given integer operation, which is known to need at most BitWidth
1918/// bits, and check for overflow in the original type (if that type was not an
1919/// unsigned type).
1920template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001921static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1922 const APSInt &LHS, const APSInt &RHS,
1923 unsigned BitWidth, Operation Op,
1924 APSInt &Result) {
1925 if (LHS.isUnsigned()) {
1926 Result = Op(LHS, RHS);
1927 return true;
1928 }
Richard Smith43e77732013-05-07 04:50:00 +00001929
1930 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001931 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001932 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001933 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001934 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001935 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001936 << Result.toString(10) << E->getType();
1937 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001938 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001939 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001940 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001941}
1942
1943/// Perform the given binary integer operation.
1944static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1945 BinaryOperatorKind Opcode, APSInt RHS,
1946 APSInt &Result) {
1947 switch (Opcode) {
1948 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001949 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00001950 return false;
1951 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001952 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1953 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001954 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00001955 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1956 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001957 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00001958 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1959 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001960 case BO_And: Result = LHS & RHS; return true;
1961 case BO_Xor: Result = LHS ^ RHS; return true;
1962 case BO_Or: Result = LHS | RHS; return true;
1963 case BO_Div:
1964 case BO_Rem:
1965 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001966 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00001967 return false;
1968 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001969 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1970 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1971 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00001972 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1973 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00001974 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1975 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001976 return true;
1977 case BO_Shl: {
1978 if (Info.getLangOpts().OpenCL)
1979 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1980 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1981 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1982 RHS.isUnsigned());
1983 else if (RHS.isSigned() && RHS.isNegative()) {
1984 // During constant-folding, a negative shift is an opposite shift. Such
1985 // a shift is not a constant expression.
1986 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1987 RHS = -RHS;
1988 goto shift_right;
1989 }
1990 shift_left:
1991 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1992 // the shifted type.
1993 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1994 if (SA != RHS) {
1995 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1996 << RHS << E->getType() << LHS.getBitWidth();
1997 } else if (LHS.isSigned()) {
1998 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1999 // operand, and must not overflow the corresponding unsigned type.
2000 if (LHS.isNegative())
2001 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2002 else if (LHS.countLeadingZeros() < SA)
2003 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2004 }
2005 Result = LHS << SA;
2006 return true;
2007 }
2008 case BO_Shr: {
2009 if (Info.getLangOpts().OpenCL)
2010 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2011 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2012 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2013 RHS.isUnsigned());
2014 else if (RHS.isSigned() && RHS.isNegative()) {
2015 // During constant-folding, a negative shift is an opposite shift. Such a
2016 // shift is not a constant expression.
2017 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2018 RHS = -RHS;
2019 goto shift_left;
2020 }
2021 shift_right:
2022 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2023 // shifted type.
2024 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2025 if (SA != RHS)
2026 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2027 << RHS << E->getType() << LHS.getBitWidth();
2028 Result = LHS >> SA;
2029 return true;
2030 }
2031
2032 case BO_LT: Result = LHS < RHS; return true;
2033 case BO_GT: Result = LHS > RHS; return true;
2034 case BO_LE: Result = LHS <= RHS; return true;
2035 case BO_GE: Result = LHS >= RHS; return true;
2036 case BO_EQ: Result = LHS == RHS; return true;
2037 case BO_NE: Result = LHS != RHS; return true;
2038 }
2039}
2040
Richard Smith861b5b52013-05-07 23:34:45 +00002041/// Perform the given binary floating-point operation, in-place, on LHS.
2042static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2043 APFloat &LHS, BinaryOperatorKind Opcode,
2044 const APFloat &RHS) {
2045 switch (Opcode) {
2046 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002047 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002048 return false;
2049 case BO_Mul:
2050 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2051 break;
2052 case BO_Add:
2053 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2054 break;
2055 case BO_Sub:
2056 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2057 break;
2058 case BO_Div:
2059 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2060 break;
2061 }
2062
Richard Smith0c6124b2015-12-03 01:36:22 +00002063 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002064 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002065 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002066 }
Richard Smith861b5b52013-05-07 23:34:45 +00002067 return true;
2068}
2069
Richard Smitha8105bc2012-01-06 16:39:00 +00002070/// Cast an lvalue referring to a base subobject to a derived class, by
2071/// truncating the lvalue's path to the given length.
2072static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2073 const RecordDecl *TruncatedType,
2074 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002075 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002076
2077 // Check we actually point to a derived class object.
2078 if (TruncatedElements == D.Entries.size())
2079 return true;
2080 assert(TruncatedElements >= D.MostDerivedPathLength &&
2081 "not casting to a derived class");
2082 if (!Result.checkSubobject(Info, E, CSK_Derived))
2083 return false;
2084
2085 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002086 const RecordDecl *RD = TruncatedType;
2087 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002088 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002089 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2090 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002091 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002092 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002093 else
Richard Smithd62306a2011-11-10 06:34:14 +00002094 Result.Offset -= Layout.getBaseClassOffset(Base);
2095 RD = Base;
2096 }
Richard Smith027bf112011-11-17 22:56:20 +00002097 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002098 return true;
2099}
2100
John McCalld7bca762012-05-01 00:38:49 +00002101static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002102 const CXXRecordDecl *Derived,
2103 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002104 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002105 if (!RL) {
2106 if (Derived->isInvalidDecl()) return false;
2107 RL = &Info.Ctx.getASTRecordLayout(Derived);
2108 }
2109
Richard Smithd62306a2011-11-10 06:34:14 +00002110 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002111 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002112 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002113}
2114
Richard Smitha8105bc2012-01-06 16:39:00 +00002115static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002116 const CXXRecordDecl *DerivedDecl,
2117 const CXXBaseSpecifier *Base) {
2118 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2119
John McCalld7bca762012-05-01 00:38:49 +00002120 if (!Base->isVirtual())
2121 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002122
Richard Smitha8105bc2012-01-06 16:39:00 +00002123 SubobjectDesignator &D = Obj.Designator;
2124 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002125 return false;
2126
Richard Smitha8105bc2012-01-06 16:39:00 +00002127 // Extract most-derived object and corresponding type.
2128 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2129 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2130 return false;
2131
2132 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002133 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002134 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2135 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002136 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002137 return true;
2138}
2139
Richard Smith84401042013-06-03 05:03:02 +00002140static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2141 QualType Type, LValue &Result) {
2142 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2143 PathE = E->path_end();
2144 PathI != PathE; ++PathI) {
2145 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2146 *PathI))
2147 return false;
2148 Type = (*PathI)->getType();
2149 }
2150 return true;
2151}
2152
Richard Smithd62306a2011-11-10 06:34:14 +00002153/// Update LVal to refer to the given field, which must be a member of the type
2154/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002155static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002156 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002157 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002158 if (!RL) {
2159 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002160 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002161 }
Richard Smithd62306a2011-11-10 06:34:14 +00002162
2163 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002164 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002165 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002166 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002167}
2168
Richard Smith1b78b3d2012-01-25 22:15:11 +00002169/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002170static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002171 LValue &LVal,
2172 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002173 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002174 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002175 return false;
2176 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002177}
2178
Richard Smithd62306a2011-11-10 06:34:14 +00002179/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002180static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2181 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002182 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2183 // extension.
2184 if (Type->isVoidType() || Type->isFunctionType()) {
2185 Size = CharUnits::One();
2186 return true;
2187 }
2188
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002189 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002190 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002191 return false;
2192 }
2193
Richard Smithd62306a2011-11-10 06:34:14 +00002194 if (!Type->isConstantSizeType()) {
2195 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002196 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002197 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002198 return false;
2199 }
2200
2201 Size = Info.Ctx.getTypeSizeInChars(Type);
2202 return true;
2203}
2204
2205/// Update a pointer value to model pointer arithmetic.
2206/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002207/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002208/// \param LVal - The pointer value to be updated.
2209/// \param EltTy - The pointee type represented by LVal.
2210/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002211static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2212 LValue &LVal, QualType EltTy,
2213 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002214 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002215 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002216 return false;
2217
Yaxun Liu402804b2016-12-15 08:09:08 +00002218 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002219 return true;
2220}
2221
Richard Smith66c96992012-02-18 22:04:06 +00002222/// Update an lvalue to refer to a component of a complex number.
2223/// \param Info - Information about the ongoing evaluation.
2224/// \param LVal - The lvalue to be updated.
2225/// \param EltTy - The complex number's component type.
2226/// \param Imag - False for the real component, true for the imaginary.
2227static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2228 LValue &LVal, QualType EltTy,
2229 bool Imag) {
2230 if (Imag) {
2231 CharUnits SizeOfComponent;
2232 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2233 return false;
2234 LVal.Offset += SizeOfComponent;
2235 }
2236 LVal.addComplex(Info, E, EltTy, Imag);
2237 return true;
2238}
2239
Richard Smith27908702011-10-24 17:54:18 +00002240/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002241///
2242/// \param Info Information about the ongoing evaluation.
2243/// \param E An expression to be used when printing diagnostics.
2244/// \param VD The variable whose initializer should be obtained.
2245/// \param Frame The frame in which the variable was created. Must be null
2246/// if this variable is not local to the evaluation.
2247/// \param Result Filled in with a pointer to the value of the variable.
2248static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2249 const VarDecl *VD, CallStackFrame *Frame,
2250 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002251 // If this is a parameter to an active constexpr function call, perform
2252 // argument substitution.
2253 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002254 // Assume arguments of a potential constant expression are unknown
2255 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002256 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002257 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002258 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002259 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002260 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002261 }
Richard Smith3229b742013-05-05 21:17:10 +00002262 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002263 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002264 }
Richard Smith27908702011-10-24 17:54:18 +00002265
Richard Smithd9f663b2013-04-22 15:31:51 +00002266 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002267 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002268 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002269 if (!Result) {
2270 // Assume variables referenced within a lambda's call operator that were
2271 // not declared within the call operator are captures and during checking
2272 // of a potential constant expression, assume they are unknown constant
2273 // expressions.
2274 assert(isLambdaCallOperator(Frame->Callee) &&
2275 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2276 "missing value for local variable");
2277 if (Info.checkingPotentialConstantExpression())
2278 return false;
2279 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002280 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002281 diag::note_unimplemented_constexpr_lambda_feature_ast)
2282 << "captures not currently allowed";
2283 return false;
2284 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002285 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002286 }
2287
Richard Smithd0b4dd62011-12-19 06:19:21 +00002288 // Dig out the initializer, and use the declaration which it's attached to.
2289 const Expr *Init = VD->getAnyInitializer(VD);
2290 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002291 // If we're checking a potential constant expression, the variable could be
2292 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002293 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002294 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002295 return false;
2296 }
2297
Richard Smithd62306a2011-11-10 06:34:14 +00002298 // If we're currently evaluating the initializer of this declaration, use that
2299 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002300 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002301 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002302 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002303 }
2304
Richard Smithcecf1842011-11-01 21:06:14 +00002305 // Never evaluate the initializer of a weak variable. We can't be sure that
2306 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002307 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002308 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002309 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002310 }
Richard Smithcecf1842011-11-01 21:06:14 +00002311
Richard Smithd0b4dd62011-12-19 06:19:21 +00002312 // Check that we can fold the initializer. In C++, we will have already done
2313 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002314 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002315 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002316 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002317 Notes.size() + 1) << VD;
2318 Info.Note(VD->getLocation(), diag::note_declared_at);
2319 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002320 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002321 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002322 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002323 Notes.size() + 1) << VD;
2324 Info.Note(VD->getLocation(), diag::note_declared_at);
2325 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002326 }
Richard Smith27908702011-10-24 17:54:18 +00002327
Richard Smith3229b742013-05-05 21:17:10 +00002328 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002329 return true;
Richard Smith27908702011-10-24 17:54:18 +00002330}
2331
Richard Smith11562c52011-10-28 17:51:58 +00002332static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002333 Qualifiers Quals = T.getQualifiers();
2334 return Quals.hasConst() && !Quals.hasVolatile();
2335}
2336
Richard Smithe97cbd72011-11-11 04:05:33 +00002337/// Get the base index of the given base class within an APValue representing
2338/// the given derived class.
2339static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2340 const CXXRecordDecl *Base) {
2341 Base = Base->getCanonicalDecl();
2342 unsigned Index = 0;
2343 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2344 E = Derived->bases_end(); I != E; ++I, ++Index) {
2345 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2346 return Index;
2347 }
2348
2349 llvm_unreachable("base class missing from derived class's bases list");
2350}
2351
Richard Smith3da88fa2013-04-26 14:36:30 +00002352/// Extract the value of a character from a string literal.
2353static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2354 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002355 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2356 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2357 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002358 const StringLiteral *S = cast<StringLiteral>(Lit);
2359 const ConstantArrayType *CAT =
2360 Info.Ctx.getAsConstantArrayType(S->getType());
2361 assert(CAT && "string literal isn't an array");
2362 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002363 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002364
2365 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002366 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002367 if (Index < S->getLength())
2368 Value = S->getCodeUnit(Index);
2369 return Value;
2370}
2371
Richard Smith3da88fa2013-04-26 14:36:30 +00002372// Expand a string literal into an array of characters.
2373static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2374 APValue &Result) {
2375 const StringLiteral *S = cast<StringLiteral>(Lit);
2376 const ConstantArrayType *CAT =
2377 Info.Ctx.getAsConstantArrayType(S->getType());
2378 assert(CAT && "string literal isn't an array");
2379 QualType CharType = CAT->getElementType();
2380 assert(CharType->isIntegerType() && "unexpected character type");
2381
2382 unsigned Elts = CAT->getSize().getZExtValue();
2383 Result = APValue(APValue::UninitArray(),
2384 std::min(S->getLength(), Elts), Elts);
2385 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2386 CharType->isUnsignedIntegerType());
2387 if (Result.hasArrayFiller())
2388 Result.getArrayFiller() = APValue(Value);
2389 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2390 Value = S->getCodeUnit(I);
2391 Result.getArrayInitializedElt(I) = APValue(Value);
2392 }
2393}
2394
2395// Expand an array so that it has more than Index filled elements.
2396static void expandArray(APValue &Array, unsigned Index) {
2397 unsigned Size = Array.getArraySize();
2398 assert(Index < Size);
2399
2400 // Always at least double the number of elements for which we store a value.
2401 unsigned OldElts = Array.getArrayInitializedElts();
2402 unsigned NewElts = std::max(Index+1, OldElts * 2);
2403 NewElts = std::min(Size, std::max(NewElts, 8u));
2404
2405 // Copy the data across.
2406 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2407 for (unsigned I = 0; I != OldElts; ++I)
2408 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2409 for (unsigned I = OldElts; I != NewElts; ++I)
2410 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2411 if (NewValue.hasArrayFiller())
2412 NewValue.getArrayFiller() = Array.getArrayFiller();
2413 Array.swap(NewValue);
2414}
2415
Richard Smithb01fe402014-09-16 01:24:02 +00002416/// Determine whether a type would actually be read by an lvalue-to-rvalue
2417/// conversion. If it's of class type, we may assume that the copy operation
2418/// is trivial. Note that this is never true for a union type with fields
2419/// (because the copy always "reads" the active member) and always true for
2420/// a non-class type.
2421static bool isReadByLvalueToRvalueConversion(QualType T) {
2422 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2423 if (!RD || (RD->isUnion() && !RD->field_empty()))
2424 return true;
2425 if (RD->isEmpty())
2426 return false;
2427
2428 for (auto *Field : RD->fields())
2429 if (isReadByLvalueToRvalueConversion(Field->getType()))
2430 return true;
2431
2432 for (auto &BaseSpec : RD->bases())
2433 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2434 return true;
2435
2436 return false;
2437}
2438
2439/// Diagnose an attempt to read from any unreadable field within the specified
2440/// type, which might be a class type.
2441static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2442 QualType T) {
2443 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2444 if (!RD)
2445 return false;
2446
2447 if (!RD->hasMutableFields())
2448 return false;
2449
2450 for (auto *Field : RD->fields()) {
2451 // If we're actually going to read this field in some way, then it can't
2452 // be mutable. If we're in a union, then assigning to a mutable field
2453 // (even an empty one) can change the active member, so that's not OK.
2454 // FIXME: Add core issue number for the union case.
2455 if (Field->isMutable() &&
2456 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002457 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002458 Info.Note(Field->getLocation(), diag::note_declared_at);
2459 return true;
2460 }
2461
2462 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2463 return true;
2464 }
2465
2466 for (auto &BaseSpec : RD->bases())
2467 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2468 return true;
2469
2470 // All mutable fields were empty, and thus not actually read.
2471 return false;
2472}
2473
Richard Smith861b5b52013-05-07 23:34:45 +00002474/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002475enum AccessKinds {
2476 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002477 AK_Assign,
2478 AK_Increment,
2479 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002480};
2481
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002482namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002483/// A handle to a complete object (an object that is not a subobject of
2484/// another object).
2485struct CompleteObject {
2486 /// The value of the complete object.
2487 APValue *Value;
2488 /// The type of the complete object.
2489 QualType Type;
2490
Craig Topper36250ad2014-05-12 05:36:57 +00002491 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002492 CompleteObject(APValue *Value, QualType Type)
2493 : Value(Value), Type(Type) {
2494 assert(Value && "missing value for complete object");
2495 }
2496
Aaron Ballman67347662015-02-15 22:00:28 +00002497 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002498};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002499} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002500
Richard Smith3da88fa2013-04-26 14:36:30 +00002501/// Find the designated sub-object of an rvalue.
2502template<typename SubobjectHandler>
2503typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002504findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002505 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002506 if (Sub.Invalid)
2507 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002508 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002509 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002510 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002511 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002512 << handler.AccessKind;
2513 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002514 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002515 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002516 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002517
Richard Smith3229b742013-05-05 21:17:10 +00002518 APValue *O = Obj.Value;
2519 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002520 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002521
Richard Smithd62306a2011-11-10 06:34:14 +00002522 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002523 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2524 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002525 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002526 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002527 return handler.failed();
2528 }
2529
Richard Smith49ca8aa2013-08-06 07:09:20 +00002530 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002531 // If we are reading an object of class type, there may still be more
2532 // things we need to check: if there are any mutable subobjects, we
2533 // cannot perform this read. (This only happens when performing a trivial
2534 // copy or assignment.)
2535 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2536 diagnoseUnreadableFields(Info, E, ObjType))
2537 return handler.failed();
2538
Richard Smith49ca8aa2013-08-06 07:09:20 +00002539 if (!handler.found(*O, ObjType))
2540 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002541
Richard Smith49ca8aa2013-08-06 07:09:20 +00002542 // If we modified a bit-field, truncate it to the right width.
2543 if (handler.AccessKind != AK_Read &&
2544 LastField && LastField->isBitField() &&
2545 !truncateBitfieldValue(Info, E, *O, LastField))
2546 return false;
2547
2548 return true;
2549 }
2550
Craig Topper36250ad2014-05-12 05:36:57 +00002551 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002552 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002553 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002554 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002555 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002556 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002557 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002558 // Note, it should not be possible to form a pointer with a valid
2559 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002560 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002561 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002562 << handler.AccessKind;
2563 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002564 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002565 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002566 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002567
2568 ObjType = CAT->getElementType();
2569
Richard Smith14a94132012-02-17 03:35:37 +00002570 // An array object is represented as either an Array APValue or as an
2571 // LValue which refers to a string literal.
2572 if (O->isLValue()) {
2573 assert(I == N - 1 && "extracting subobject of character?");
2574 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002575 if (handler.AccessKind != AK_Read)
2576 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2577 *O);
2578 else
2579 return handler.foundString(*O, ObjType, Index);
2580 }
2581
2582 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002583 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002584 else if (handler.AccessKind != AK_Read) {
2585 expandArray(*O, Index);
2586 O = &O->getArrayInitializedElt(Index);
2587 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002588 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002589 } else if (ObjType->isAnyComplexType()) {
2590 // Next subobject is a complex number.
2591 uint64_t Index = Sub.Entries[I].ArrayIndex;
2592 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002593 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002594 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002595 << handler.AccessKind;
2596 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002597 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002598 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002599 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002600
2601 bool WasConstQualified = ObjType.isConstQualified();
2602 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2603 if (WasConstQualified)
2604 ObjType.addConst();
2605
Richard Smith66c96992012-02-18 22:04:06 +00002606 assert(I == N - 1 && "extracting subobject of scalar?");
2607 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002608 return handler.found(Index ? O->getComplexIntImag()
2609 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002610 } else {
2611 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002612 return handler.found(Index ? O->getComplexFloatImag()
2613 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002614 }
Richard Smithd62306a2011-11-10 06:34:14 +00002615 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002616 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002617 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002618 << Field;
2619 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002620 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002621 }
2622
Richard Smithd62306a2011-11-10 06:34:14 +00002623 // Next subobject is a class, struct or union field.
2624 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2625 if (RD->isUnion()) {
2626 const FieldDecl *UnionField = O->getUnionField();
2627 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002628 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002629 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002630 << handler.AccessKind << Field << !UnionField << UnionField;
2631 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002632 }
Richard Smithd62306a2011-11-10 06:34:14 +00002633 O = &O->getUnionValue();
2634 } else
2635 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002636
2637 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002638 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002639 if (WasConstQualified && !Field->isMutable())
2640 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002641
2642 if (ObjType.isVolatileQualified()) {
2643 if (Info.getLangOpts().CPlusPlus) {
2644 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002645 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002646 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002647 Info.Note(Field->getLocation(), diag::note_declared_at);
2648 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002649 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002650 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002651 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002652 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002653
2654 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002655 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002656 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002657 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2658 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2659 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002660
2661 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002662 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002663 if (WasConstQualified)
2664 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002665 }
2666 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002667}
2668
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002669namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002670struct ExtractSubobjectHandler {
2671 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002672 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002673
2674 static const AccessKinds AccessKind = AK_Read;
2675
2676 typedef bool result_type;
2677 bool failed() { return false; }
2678 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002679 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002680 return true;
2681 }
2682 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002683 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002684 return true;
2685 }
2686 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002687 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002688 return true;
2689 }
2690 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002691 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002692 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2693 return true;
2694 }
2695};
Richard Smith3229b742013-05-05 21:17:10 +00002696} // end anonymous namespace
2697
Richard Smith3da88fa2013-04-26 14:36:30 +00002698const AccessKinds ExtractSubobjectHandler::AccessKind;
2699
2700/// Extract the designated sub-object of an rvalue.
2701static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002702 const CompleteObject &Obj,
2703 const SubobjectDesignator &Sub,
2704 APValue &Result) {
2705 ExtractSubobjectHandler Handler = { Info, Result };
2706 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002707}
2708
Richard Smith3229b742013-05-05 21:17:10 +00002709namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002710struct ModifySubobjectHandler {
2711 EvalInfo &Info;
2712 APValue &NewVal;
2713 const Expr *E;
2714
2715 typedef bool result_type;
2716 static const AccessKinds AccessKind = AK_Assign;
2717
2718 bool checkConst(QualType QT) {
2719 // Assigning to a const object has undefined behavior.
2720 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002721 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002722 return false;
2723 }
2724 return true;
2725 }
2726
2727 bool failed() { return false; }
2728 bool found(APValue &Subobj, QualType SubobjType) {
2729 if (!checkConst(SubobjType))
2730 return false;
2731 // We've been given ownership of NewVal, so just swap it in.
2732 Subobj.swap(NewVal);
2733 return true;
2734 }
2735 bool found(APSInt &Value, QualType SubobjType) {
2736 if (!checkConst(SubobjType))
2737 return false;
2738 if (!NewVal.isInt()) {
2739 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002740 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002741 return false;
2742 }
2743 Value = NewVal.getInt();
2744 return true;
2745 }
2746 bool found(APFloat &Value, QualType SubobjType) {
2747 if (!checkConst(SubobjType))
2748 return false;
2749 Value = NewVal.getFloat();
2750 return true;
2751 }
2752 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2753 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2754 }
2755};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002756} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002757
Richard Smith3229b742013-05-05 21:17:10 +00002758const AccessKinds ModifySubobjectHandler::AccessKind;
2759
Richard Smith3da88fa2013-04-26 14:36:30 +00002760/// Update the designated sub-object of an rvalue to the given value.
2761static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002762 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002763 const SubobjectDesignator &Sub,
2764 APValue &NewVal) {
2765 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002766 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002767}
2768
Richard Smith84f6dcf2012-02-02 01:16:57 +00002769/// Find the position where two subobject designators diverge, or equivalently
2770/// the length of the common initial subsequence.
2771static unsigned FindDesignatorMismatch(QualType ObjType,
2772 const SubobjectDesignator &A,
2773 const SubobjectDesignator &B,
2774 bool &WasArrayIndex) {
2775 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2776 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002777 if (!ObjType.isNull() &&
2778 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002779 // Next subobject is an array element.
2780 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2781 WasArrayIndex = true;
2782 return I;
2783 }
Richard Smith66c96992012-02-18 22:04:06 +00002784 if (ObjType->isAnyComplexType())
2785 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2786 else
2787 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002788 } else {
2789 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2790 WasArrayIndex = false;
2791 return I;
2792 }
2793 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2794 // Next subobject is a field.
2795 ObjType = FD->getType();
2796 else
2797 // Next subobject is a base class.
2798 ObjType = QualType();
2799 }
2800 }
2801 WasArrayIndex = false;
2802 return I;
2803}
2804
2805/// Determine whether the given subobject designators refer to elements of the
2806/// same array object.
2807static bool AreElementsOfSameArray(QualType ObjType,
2808 const SubobjectDesignator &A,
2809 const SubobjectDesignator &B) {
2810 if (A.Entries.size() != B.Entries.size())
2811 return false;
2812
George Burgess IVa51c4072015-10-16 01:49:01 +00002813 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002814 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2815 // A is a subobject of the array element.
2816 return false;
2817
2818 // If A (and B) designates an array element, the last entry will be the array
2819 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2820 // of length 1' case, and the entire path must match.
2821 bool WasArrayIndex;
2822 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2823 return CommonLength >= A.Entries.size() - IsArray;
2824}
2825
Richard Smith3229b742013-05-05 21:17:10 +00002826/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002827static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2828 AccessKinds AK, const LValue &LVal,
2829 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002830 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002831 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002832 return CompleteObject();
2833 }
2834
Craig Topper36250ad2014-05-12 05:36:57 +00002835 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002836 if (LVal.CallIndex) {
2837 Frame = Info.getCallFrame(LVal.CallIndex);
2838 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002839 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002840 << AK << LVal.Base.is<const ValueDecl*>();
2841 NoteLValueLocation(Info, LVal.Base);
2842 return CompleteObject();
2843 }
Richard Smith3229b742013-05-05 21:17:10 +00002844 }
2845
2846 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2847 // is not a constant expression (even if the object is non-volatile). We also
2848 // apply this rule to C++98, in order to conform to the expected 'volatile'
2849 // semantics.
2850 if (LValType.isVolatileQualified()) {
2851 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002852 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002853 << AK << LValType;
2854 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002855 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002856 return CompleteObject();
2857 }
2858
2859 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002860 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002861 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002862
2863 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2864 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2865 // In C++11, constexpr, non-volatile variables initialized with constant
2866 // expressions are constant expressions too. Inside constexpr functions,
2867 // parameters are constant expressions even if they're non-const.
2868 // In C++1y, objects local to a constant expression (those with a Frame) are
2869 // both readable and writable inside constant expressions.
2870 // In C, such things can also be folded, although they are not ICEs.
2871 const VarDecl *VD = dyn_cast<VarDecl>(D);
2872 if (VD) {
2873 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2874 VD = VDef;
2875 }
2876 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002877 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002878 return CompleteObject();
2879 }
2880
2881 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002882 if (BaseType.isVolatileQualified()) {
2883 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002884 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002885 << AK << 1 << VD;
2886 Info.Note(VD->getLocation(), diag::note_declared_at);
2887 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002888 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002889 }
2890 return CompleteObject();
2891 }
2892
2893 // Unless we're looking at a local variable or argument in a constexpr call,
2894 // the variable we're reading must be const.
2895 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002896 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002897 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2898 // OK, we can read and modify an object if we're in the process of
2899 // evaluating its initializer, because its lifetime began in this
2900 // evaluation.
2901 } else if (AK != AK_Read) {
2902 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002903 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002904 return CompleteObject();
George Burgess IVa7470272016-12-20 01:05:42 +00002905 } else if (VD->isConstexpr() || BaseType.isConstQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002906 // OK, we can read this variable.
2907 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002908 // In OpenCL if a variable is in constant address space it is a const value.
2909 if (!(BaseType.isConstQualified() ||
2910 (Info.getLangOpts().OpenCL &&
2911 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002912 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002913 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002914 Info.Note(VD->getLocation(), diag::note_declared_at);
2915 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002916 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002917 }
2918 return CompleteObject();
2919 }
2920 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2921 // We support folding of const floating-point types, in order to make
2922 // static const data members of such types (supported as an extension)
2923 // more useful.
2924 if (Info.getLangOpts().CPlusPlus11) {
2925 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2926 Info.Note(VD->getLocation(), diag::note_declared_at);
2927 } else {
2928 Info.CCEDiag(E);
2929 }
2930 } else {
2931 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00002932 if (Info.checkingPotentialConstantExpression() &&
2933 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2934 // The definition of this variable could be constexpr. We can't
2935 // access it right now, but may be able to in future.
2936 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002937 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002938 Info.Note(VD->getLocation(), diag::note_declared_at);
2939 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002940 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002941 }
2942 return CompleteObject();
2943 }
2944 }
2945
2946 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2947 return CompleteObject();
2948 } else {
2949 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2950
2951 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002952 if (const MaterializeTemporaryExpr *MTE =
2953 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2954 assert(MTE->getStorageDuration() == SD_Static &&
2955 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002956
Richard Smithe6c01442013-06-05 00:46:14 +00002957 // Per C++1y [expr.const]p2:
2958 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2959 // - a [...] glvalue of integral or enumeration type that refers to
2960 // a non-volatile const object [...]
2961 // [...]
2962 // - a [...] glvalue of literal type that refers to a non-volatile
2963 // object whose lifetime began within the evaluation of e.
2964 //
2965 // C++11 misses the 'began within the evaluation of e' check and
2966 // instead allows all temporaries, including things like:
2967 // int &&r = 1;
2968 // int x = ++r;
2969 // constexpr int k = r;
2970 // Therefore we use the C++1y rules in C++11 too.
2971 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2972 const ValueDecl *ED = MTE->getExtendingDecl();
2973 if (!(BaseType.isConstQualified() &&
2974 BaseType->isIntegralOrEnumerationType()) &&
2975 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002976 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00002977 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2978 return CompleteObject();
2979 }
2980
2981 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2982 assert(BaseVal && "got reference to unevaluated temporary");
2983 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002984 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00002985 return CompleteObject();
2986 }
2987 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002988 BaseVal = Frame->getTemporary(Base);
2989 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002990 }
Richard Smith3229b742013-05-05 21:17:10 +00002991
2992 // Volatile temporary objects cannot be accessed in constant expressions.
2993 if (BaseType.isVolatileQualified()) {
2994 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002995 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002996 << AK << 0;
2997 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2998 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002999 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003000 }
3001 return CompleteObject();
3002 }
3003 }
3004
Richard Smith7525ff62013-05-09 07:14:00 +00003005 // During the construction of an object, it is not yet 'const'.
3006 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3007 // and this doesn't do quite the right thing for const subobjects of the
3008 // object under construction.
3009 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3010 BaseType = Info.Ctx.getCanonicalType(BaseType);
3011 BaseType.removeLocalConst();
3012 }
3013
Richard Smith6d4c6582013-11-05 22:18:15 +00003014 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003015 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003016 //
3017 // FIXME: Not all local state is mutable. Allow local constant subobjects
3018 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003019 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3020 Info.EvalStatus.HasSideEffects) ||
3021 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003022 return CompleteObject();
3023
3024 return CompleteObject(BaseVal, BaseType);
3025}
3026
Richard Smith243ef902013-05-05 23:31:59 +00003027/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3028/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3029/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003030///
3031/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003032/// \param Conv - The expression for which we are performing the conversion.
3033/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003034/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3035/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003036/// \param LVal - The glvalue on which we are attempting to perform this action.
3037/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003038static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003039 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003040 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003041 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003042 return false;
3043
Richard Smith3229b742013-05-05 21:17:10 +00003044 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003045 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003046 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003047 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3048 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3049 // initializer until now for such expressions. Such an expression can't be
3050 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003051 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003052 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003053 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003054 }
Richard Smith3229b742013-05-05 21:17:10 +00003055 APValue Lit;
3056 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3057 return false;
3058 CompleteObject LitObj(&Lit, Base->getType());
3059 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003060 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003061 // We represent a string literal array as an lvalue pointing at the
3062 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003063 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003064 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3065 CompleteObject StrObj(&Str, Base->getType());
3066 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003067 }
Richard Smith11562c52011-10-28 17:51:58 +00003068 }
3069
Richard Smith3229b742013-05-05 21:17:10 +00003070 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3071 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003072}
3073
3074/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003075static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003076 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003077 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003078 return false;
3079
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003080 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003081 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003082 return false;
3083 }
3084
Richard Smith3229b742013-05-05 21:17:10 +00003085 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3086 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00003087}
3088
Richard Smith243ef902013-05-05 23:31:59 +00003089static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3090 return T->isSignedIntegerType() &&
3091 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3092}
3093
3094namespace {
Richard Smith43e77732013-05-07 04:50:00 +00003095struct CompoundAssignSubobjectHandler {
3096 EvalInfo &Info;
3097 const Expr *E;
3098 QualType PromotedLHSType;
3099 BinaryOperatorKind Opcode;
3100 const APValue &RHS;
3101
3102 static const AccessKinds AccessKind = AK_Assign;
3103
3104 typedef bool result_type;
3105
3106 bool checkConst(QualType QT) {
3107 // Assigning to a const object has undefined behavior.
3108 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003109 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003110 return false;
3111 }
3112 return true;
3113 }
3114
3115 bool failed() { return false; }
3116 bool found(APValue &Subobj, QualType SubobjType) {
3117 switch (Subobj.getKind()) {
3118 case APValue::Int:
3119 return found(Subobj.getInt(), SubobjType);
3120 case APValue::Float:
3121 return found(Subobj.getFloat(), SubobjType);
3122 case APValue::ComplexInt:
3123 case APValue::ComplexFloat:
3124 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003125 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003126 return false;
3127 case APValue::LValue:
3128 return foundPointer(Subobj, SubobjType);
3129 default:
3130 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003131 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003132 return false;
3133 }
3134 }
3135 bool found(APSInt &Value, QualType SubobjType) {
3136 if (!checkConst(SubobjType))
3137 return false;
3138
3139 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3140 // We don't support compound assignment on integer-cast-to-pointer
3141 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003142 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003143 return false;
3144 }
3145
3146 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3147 SubobjType, Value);
3148 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3149 return false;
3150 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3151 return true;
3152 }
3153 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003154 return checkConst(SubobjType) &&
3155 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3156 Value) &&
3157 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3158 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003159 }
3160 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3161 if (!checkConst(SubobjType))
3162 return false;
3163
3164 QualType PointeeType;
3165 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3166 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003167
3168 if (PointeeType.isNull() || !RHS.isInt() ||
3169 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003170 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003171 return false;
3172 }
3173
Richard Smith861b5b52013-05-07 23:34:45 +00003174 int64_t Offset = getExtValue(RHS.getInt());
3175 if (Opcode == BO_Sub)
3176 Offset = -Offset;
3177
3178 LValue LVal;
3179 LVal.setFrom(Info.Ctx, Subobj);
3180 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3181 return false;
3182 LVal.moveInto(Subobj);
3183 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003184 }
3185 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3186 llvm_unreachable("shouldn't encounter string elements here");
3187 }
3188};
3189} // end anonymous namespace
3190
3191const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3192
3193/// Perform a compound assignment of LVal <op>= RVal.
3194static bool handleCompoundAssignment(
3195 EvalInfo &Info, const Expr *E,
3196 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3197 BinaryOperatorKind Opcode, const APValue &RVal) {
3198 if (LVal.Designator.Invalid)
3199 return false;
3200
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003201 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003202 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003203 return false;
3204 }
3205
3206 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3207 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3208 RVal };
3209 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3210}
3211
3212namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003213struct IncDecSubobjectHandler {
3214 EvalInfo &Info;
3215 const Expr *E;
3216 AccessKinds AccessKind;
3217 APValue *Old;
3218
3219 typedef bool result_type;
3220
3221 bool checkConst(QualType QT) {
3222 // Assigning to a const object has undefined behavior.
3223 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003224 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003225 return false;
3226 }
3227 return true;
3228 }
3229
3230 bool failed() { return false; }
3231 bool found(APValue &Subobj, QualType SubobjType) {
3232 // Stash the old value. Also clear Old, so we don't clobber it later
3233 // if we're post-incrementing a complex.
3234 if (Old) {
3235 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003236 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003237 }
3238
3239 switch (Subobj.getKind()) {
3240 case APValue::Int:
3241 return found(Subobj.getInt(), SubobjType);
3242 case APValue::Float:
3243 return found(Subobj.getFloat(), SubobjType);
3244 case APValue::ComplexInt:
3245 return found(Subobj.getComplexIntReal(),
3246 SubobjType->castAs<ComplexType>()->getElementType()
3247 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3248 case APValue::ComplexFloat:
3249 return found(Subobj.getComplexFloatReal(),
3250 SubobjType->castAs<ComplexType>()->getElementType()
3251 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3252 case APValue::LValue:
3253 return foundPointer(Subobj, SubobjType);
3254 default:
3255 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003256 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003257 return false;
3258 }
3259 }
3260 bool found(APSInt &Value, QualType SubobjType) {
3261 if (!checkConst(SubobjType))
3262 return false;
3263
3264 if (!SubobjType->isIntegerType()) {
3265 // We don't support increment / decrement on integer-cast-to-pointer
3266 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003267 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003268 return false;
3269 }
3270
3271 if (Old) *Old = APValue(Value);
3272
3273 // bool arithmetic promotes to int, and the conversion back to bool
3274 // doesn't reduce mod 2^n, so special-case it.
3275 if (SubobjType->isBooleanType()) {
3276 if (AccessKind == AK_Increment)
3277 Value = 1;
3278 else
3279 Value = !Value;
3280 return true;
3281 }
3282
3283 bool WasNegative = Value.isNegative();
3284 if (AccessKind == AK_Increment) {
3285 ++Value;
3286
3287 if (!WasNegative && Value.isNegative() &&
3288 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3289 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003290 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003291 }
3292 } else {
3293 --Value;
3294
3295 if (WasNegative && !Value.isNegative() &&
3296 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3297 unsigned BitWidth = Value.getBitWidth();
3298 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3299 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003300 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003301 }
3302 }
3303 return true;
3304 }
3305 bool found(APFloat &Value, QualType SubobjType) {
3306 if (!checkConst(SubobjType))
3307 return false;
3308
3309 if (Old) *Old = APValue(Value);
3310
3311 APFloat One(Value.getSemantics(), 1);
3312 if (AccessKind == AK_Increment)
3313 Value.add(One, APFloat::rmNearestTiesToEven);
3314 else
3315 Value.subtract(One, APFloat::rmNearestTiesToEven);
3316 return true;
3317 }
3318 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3319 if (!checkConst(SubobjType))
3320 return false;
3321
3322 QualType PointeeType;
3323 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3324 PointeeType = PT->getPointeeType();
3325 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003326 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003327 return false;
3328 }
3329
3330 LValue LVal;
3331 LVal.setFrom(Info.Ctx, Subobj);
3332 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3333 AccessKind == AK_Increment ? 1 : -1))
3334 return false;
3335 LVal.moveInto(Subobj);
3336 return true;
3337 }
3338 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3339 llvm_unreachable("shouldn't encounter string elements here");
3340 }
3341};
3342} // end anonymous namespace
3343
3344/// Perform an increment or decrement on LVal.
3345static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3346 QualType LValType, bool IsIncrement, APValue *Old) {
3347 if (LVal.Designator.Invalid)
3348 return false;
3349
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003350 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003351 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003352 return false;
3353 }
3354
3355 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3356 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3357 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3358 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3359}
3360
Richard Smithe97cbd72011-11-11 04:05:33 +00003361/// Build an lvalue for the object argument of a member function call.
3362static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3363 LValue &This) {
3364 if (Object->getType()->isPointerType())
3365 return EvaluatePointer(Object, This, Info);
3366
3367 if (Object->isGLValue())
3368 return EvaluateLValue(Object, This, Info);
3369
Richard Smithd9f663b2013-04-22 15:31:51 +00003370 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003371 return EvaluateTemporary(Object, This, Info);
3372
Faisal Valie690b7a2016-07-02 22:34:24 +00003373 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003374 return false;
3375}
3376
3377/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3378/// lvalue referring to the result.
3379///
3380/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003381/// \param LV - An lvalue referring to the base of the member pointer.
3382/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003383/// \param IncludeMember - Specifies whether the member itself is included in
3384/// the resulting LValue subobject designator. This is not possible when
3385/// creating a bound member function.
3386/// \return The field or method declaration to which the member pointer refers,
3387/// or 0 if evaluation fails.
3388static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003389 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003390 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003391 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003392 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003393 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003394 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003395 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003396
3397 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3398 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003399 if (!MemPtr.getDecl()) {
3400 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003401 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003402 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003403 }
Richard Smith253c2a32012-01-27 01:14:48 +00003404
Richard Smith027bf112011-11-17 22:56:20 +00003405 if (MemPtr.isDerivedMember()) {
3406 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003407 // The end of the derived-to-base path for the base object must match the
3408 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003409 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003410 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003411 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003412 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003413 }
Richard Smith027bf112011-11-17 22:56:20 +00003414 unsigned PathLengthToMember =
3415 LV.Designator.Entries.size() - MemPtr.Path.size();
3416 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3417 const CXXRecordDecl *LVDecl = getAsBaseClass(
3418 LV.Designator.Entries[PathLengthToMember + I]);
3419 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003420 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003421 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003422 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003423 }
Richard Smith027bf112011-11-17 22:56:20 +00003424 }
3425
3426 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003427 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003428 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003429 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003430 } else if (!MemPtr.Path.empty()) {
3431 // Extend the LValue path with the member pointer's path.
3432 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3433 MemPtr.Path.size() + IncludeMember);
3434
3435 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003436 if (const PointerType *PT = LVType->getAs<PointerType>())
3437 LVType = PT->getPointeeType();
3438 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3439 assert(RD && "member pointer access on non-class-type expression");
3440 // The first class in the path is that of the lvalue.
3441 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3442 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003443 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003444 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003445 RD = Base;
3446 }
3447 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003448 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3449 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003450 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003451 }
3452
3453 // Add the member. Note that we cannot build bound member functions here.
3454 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003455 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003456 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003457 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003458 } else if (const IndirectFieldDecl *IFD =
3459 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003460 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003461 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003462 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003463 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003464 }
Richard Smith027bf112011-11-17 22:56:20 +00003465 }
3466
3467 return MemPtr.getDecl();
3468}
3469
Richard Smith84401042013-06-03 05:03:02 +00003470static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3471 const BinaryOperator *BO,
3472 LValue &LV,
3473 bool IncludeMember = true) {
3474 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3475
3476 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003477 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003478 MemberPtr MemPtr;
3479 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3480 }
Craig Topper36250ad2014-05-12 05:36:57 +00003481 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003482 }
3483
3484 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3485 BO->getRHS(), IncludeMember);
3486}
3487
Richard Smith027bf112011-11-17 22:56:20 +00003488/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3489/// the provided lvalue, which currently refers to the base object.
3490static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3491 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003492 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003493 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003494 return false;
3495
Richard Smitha8105bc2012-01-06 16:39:00 +00003496 QualType TargetQT = E->getType();
3497 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3498 TargetQT = PT->getPointeeType();
3499
3500 // Check this cast lands within the final derived-to-base subobject path.
3501 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003502 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003503 << D.MostDerivedType << TargetQT;
3504 return false;
3505 }
3506
Richard Smith027bf112011-11-17 22:56:20 +00003507 // Check the type of the final cast. We don't need to check the path,
3508 // since a cast can only be formed if the path is unique.
3509 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003510 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3511 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003512 if (NewEntriesSize == D.MostDerivedPathLength)
3513 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3514 else
Richard Smith027bf112011-11-17 22:56:20 +00003515 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003516 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003517 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003518 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003519 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003520 }
Richard Smith027bf112011-11-17 22:56:20 +00003521
3522 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003523 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003524}
3525
Mike Stump876387b2009-10-27 22:09:17 +00003526namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003527enum EvalStmtResult {
3528 /// Evaluation failed.
3529 ESR_Failed,
3530 /// Hit a 'return' statement.
3531 ESR_Returned,
3532 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003533 ESR_Succeeded,
3534 /// Hit a 'continue' statement.
3535 ESR_Continue,
3536 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003537 ESR_Break,
3538 /// Still scanning for 'case' or 'default' statement.
3539 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003540};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003541}
Richard Smith254a73d2011-10-28 22:34:42 +00003542
Richard Smith97fcf4b2016-08-14 23:15:52 +00003543static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3544 // We don't need to evaluate the initializer for a static local.
3545 if (!VD->hasLocalStorage())
3546 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003547
Richard Smith97fcf4b2016-08-14 23:15:52 +00003548 LValue Result;
3549 Result.set(VD, Info.CurrentCall->Index);
3550 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003551
Richard Smith97fcf4b2016-08-14 23:15:52 +00003552 const Expr *InitE = VD->getInit();
3553 if (!InitE) {
3554 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3555 << false << VD->getType();
3556 Val = APValue();
3557 return false;
3558 }
Richard Smith51f03172013-06-20 03:00:05 +00003559
Richard Smith97fcf4b2016-08-14 23:15:52 +00003560 if (InitE->isValueDependent())
3561 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003562
Richard Smith97fcf4b2016-08-14 23:15:52 +00003563 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3564 // Wipe out any partially-computed value, to allow tracking that this
3565 // evaluation failed.
3566 Val = APValue();
3567 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003568 }
3569
3570 return true;
3571}
3572
Richard Smith97fcf4b2016-08-14 23:15:52 +00003573static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3574 bool OK = true;
3575
3576 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3577 OK &= EvaluateVarDecl(Info, VD);
3578
3579 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3580 for (auto *BD : DD->bindings())
3581 if (auto *VD = BD->getHoldingVar())
3582 OK &= EvaluateDecl(Info, VD);
3583
3584 return OK;
3585}
3586
3587
Richard Smith4e18ca52013-05-06 05:56:11 +00003588/// Evaluate a condition (either a variable declaration or an expression).
3589static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3590 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003591 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003592 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3593 return false;
3594 return EvaluateAsBooleanCondition(Cond, Result, Info);
3595}
3596
Richard Smith89210072016-04-04 23:29:43 +00003597namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003598/// \brief A location where the result (returned value) of evaluating a
3599/// statement should be stored.
3600struct StmtResult {
3601 /// The APValue that should be filled in with the returned value.
3602 APValue &Value;
3603 /// The location containing the result, if any (used to support RVO).
3604 const LValue *Slot;
3605};
Richard Smith89210072016-04-04 23:29:43 +00003606}
Richard Smith52a980a2015-08-28 02:43:42 +00003607
3608static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003609 const Stmt *S,
3610 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003611
3612/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003613static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003614 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003615 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003616 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003617 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003618 case ESR_Break:
3619 return ESR_Succeeded;
3620 case ESR_Succeeded:
3621 case ESR_Continue:
3622 return ESR_Continue;
3623 case ESR_Failed:
3624 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003625 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003626 return ESR;
3627 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003628 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003629}
3630
Richard Smith496ddcf2013-05-12 17:32:42 +00003631/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003632static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003633 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003634 BlockScopeRAII Scope(Info);
3635
Richard Smith496ddcf2013-05-12 17:32:42 +00003636 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003637 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003638 {
3639 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003640 if (const Stmt *Init = SS->getInit()) {
3641 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3642 if (ESR != ESR_Succeeded)
3643 return ESR;
3644 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003645 if (SS->getConditionVariable() &&
3646 !EvaluateDecl(Info, SS->getConditionVariable()))
3647 return ESR_Failed;
3648 if (!EvaluateInteger(SS->getCond(), Value, Info))
3649 return ESR_Failed;
3650 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003651
3652 // Find the switch case corresponding to the value of the condition.
3653 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003654 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003655 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3656 SC = SC->getNextSwitchCase()) {
3657 if (isa<DefaultStmt>(SC)) {
3658 Found = SC;
3659 continue;
3660 }
3661
3662 const CaseStmt *CS = cast<CaseStmt>(SC);
3663 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3664 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3665 : LHS;
3666 if (LHS <= Value && Value <= RHS) {
3667 Found = SC;
3668 break;
3669 }
3670 }
3671
3672 if (!Found)
3673 return ESR_Succeeded;
3674
3675 // Search the switch body for the switch case and evaluate it from there.
3676 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3677 case ESR_Break:
3678 return ESR_Succeeded;
3679 case ESR_Succeeded:
3680 case ESR_Continue:
3681 case ESR_Failed:
3682 case ESR_Returned:
3683 return ESR;
3684 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003685 // This can only happen if the switch case is nested within a statement
3686 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003687 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003688 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003689 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003690 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003691}
3692
Richard Smith254a73d2011-10-28 22:34:42 +00003693// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003694static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003695 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003696 if (!Info.nextStep(S))
3697 return ESR_Failed;
3698
Richard Smith496ddcf2013-05-12 17:32:42 +00003699 // If we're hunting down a 'case' or 'default' label, recurse through
3700 // substatements until we hit the label.
3701 if (Case) {
3702 // FIXME: We don't start the lifetime of objects whose initialization we
3703 // jump over. However, such objects must be of class type with a trivial
3704 // default constructor that initialize all subobjects, so must be empty,
3705 // so this almost never matters.
3706 switch (S->getStmtClass()) {
3707 case Stmt::CompoundStmtClass:
3708 // FIXME: Precompute which substatement of a compound statement we
3709 // would jump to, and go straight there rather than performing a
3710 // linear scan each time.
3711 case Stmt::LabelStmtClass:
3712 case Stmt::AttributedStmtClass:
3713 case Stmt::DoStmtClass:
3714 break;
3715
3716 case Stmt::CaseStmtClass:
3717 case Stmt::DefaultStmtClass:
3718 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003719 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003720 break;
3721
3722 case Stmt::IfStmtClass: {
3723 // FIXME: Precompute which side of an 'if' we would jump to, and go
3724 // straight there rather than scanning both sides.
3725 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003726
3727 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3728 // preceded by our switch label.
3729 BlockScopeRAII Scope(Info);
3730
Richard Smith496ddcf2013-05-12 17:32:42 +00003731 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3732 if (ESR != ESR_CaseNotFound || !IS->getElse())
3733 return ESR;
3734 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3735 }
3736
3737 case Stmt::WhileStmtClass: {
3738 EvalStmtResult ESR =
3739 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3740 if (ESR != ESR_Continue)
3741 return ESR;
3742 break;
3743 }
3744
3745 case Stmt::ForStmtClass: {
3746 const ForStmt *FS = cast<ForStmt>(S);
3747 EvalStmtResult ESR =
3748 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3749 if (ESR != ESR_Continue)
3750 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003751 if (FS->getInc()) {
3752 FullExpressionRAII IncScope(Info);
3753 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3754 return ESR_Failed;
3755 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003756 break;
3757 }
3758
3759 case Stmt::DeclStmtClass:
3760 // FIXME: If the variable has initialization that can't be jumped over,
3761 // bail out of any immediately-surrounding compound-statement too.
3762 default:
3763 return ESR_CaseNotFound;
3764 }
3765 }
3766
Richard Smith254a73d2011-10-28 22:34:42 +00003767 switch (S->getStmtClass()) {
3768 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003769 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003770 // Don't bother evaluating beyond an expression-statement which couldn't
3771 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003772 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003773 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003774 return ESR_Failed;
3775 return ESR_Succeeded;
3776 }
3777
Faisal Valie690b7a2016-07-02 22:34:24 +00003778 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003779 return ESR_Failed;
3780
3781 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003782 return ESR_Succeeded;
3783
Richard Smithd9f663b2013-04-22 15:31:51 +00003784 case Stmt::DeclStmtClass: {
3785 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003786 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003787 // Each declaration initialization is its own full-expression.
3788 // FIXME: This isn't quite right; if we're performing aggregate
3789 // initialization, each braced subexpression is its own full-expression.
3790 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003791 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003792 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003793 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003794 return ESR_Succeeded;
3795 }
3796
Richard Smith357362d2011-12-13 06:39:58 +00003797 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003798 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003799 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003800 if (RetExpr &&
3801 !(Result.Slot
3802 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3803 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003804 return ESR_Failed;
3805 return ESR_Returned;
3806 }
Richard Smith254a73d2011-10-28 22:34:42 +00003807
3808 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003809 BlockScopeRAII Scope(Info);
3810
Richard Smith254a73d2011-10-28 22:34:42 +00003811 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003812 for (const auto *BI : CS->body()) {
3813 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003814 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003815 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003816 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003817 return ESR;
3818 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003819 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003820 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003821
3822 case Stmt::IfStmtClass: {
3823 const IfStmt *IS = cast<IfStmt>(S);
3824
3825 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003826 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003827 if (const Stmt *Init = IS->getInit()) {
3828 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3829 if (ESR != ESR_Succeeded)
3830 return ESR;
3831 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003832 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003833 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003834 return ESR_Failed;
3835
3836 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3837 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3838 if (ESR != ESR_Succeeded)
3839 return ESR;
3840 }
3841 return ESR_Succeeded;
3842 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003843
3844 case Stmt::WhileStmtClass: {
3845 const WhileStmt *WS = cast<WhileStmt>(S);
3846 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003847 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003848 bool Continue;
3849 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3850 Continue))
3851 return ESR_Failed;
3852 if (!Continue)
3853 break;
3854
3855 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3856 if (ESR != ESR_Continue)
3857 return ESR;
3858 }
3859 return ESR_Succeeded;
3860 }
3861
3862 case Stmt::DoStmtClass: {
3863 const DoStmt *DS = cast<DoStmt>(S);
3864 bool Continue;
3865 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003866 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003867 if (ESR != ESR_Continue)
3868 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003869 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003870
Richard Smith08d6a2c2013-07-24 07:11:57 +00003871 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003872 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3873 return ESR_Failed;
3874 } while (Continue);
3875 return ESR_Succeeded;
3876 }
3877
3878 case Stmt::ForStmtClass: {
3879 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003880 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003881 if (FS->getInit()) {
3882 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3883 if (ESR != ESR_Succeeded)
3884 return ESR;
3885 }
3886 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003887 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003888 bool Continue = true;
3889 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3890 FS->getCond(), Continue))
3891 return ESR_Failed;
3892 if (!Continue)
3893 break;
3894
3895 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3896 if (ESR != ESR_Continue)
3897 return ESR;
3898
Richard Smith08d6a2c2013-07-24 07:11:57 +00003899 if (FS->getInc()) {
3900 FullExpressionRAII IncScope(Info);
3901 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3902 return ESR_Failed;
3903 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003904 }
3905 return ESR_Succeeded;
3906 }
3907
Richard Smith896e0d72013-05-06 06:51:17 +00003908 case Stmt::CXXForRangeStmtClass: {
3909 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003910 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003911
3912 // Initialize the __range variable.
3913 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3914 if (ESR != ESR_Succeeded)
3915 return ESR;
3916
3917 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003918 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3919 if (ESR != ESR_Succeeded)
3920 return ESR;
3921 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003922 if (ESR != ESR_Succeeded)
3923 return ESR;
3924
3925 while (true) {
3926 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003927 {
3928 bool Continue = true;
3929 FullExpressionRAII CondExpr(Info);
3930 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3931 return ESR_Failed;
3932 if (!Continue)
3933 break;
3934 }
Richard Smith896e0d72013-05-06 06:51:17 +00003935
3936 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003937 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003938 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3939 if (ESR != ESR_Succeeded)
3940 return ESR;
3941
3942 // Loop body.
3943 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3944 if (ESR != ESR_Continue)
3945 return ESR;
3946
3947 // Increment: ++__begin
3948 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3949 return ESR_Failed;
3950 }
3951
3952 return ESR_Succeeded;
3953 }
3954
Richard Smith496ddcf2013-05-12 17:32:42 +00003955 case Stmt::SwitchStmtClass:
3956 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3957
Richard Smith4e18ca52013-05-06 05:56:11 +00003958 case Stmt::ContinueStmtClass:
3959 return ESR_Continue;
3960
3961 case Stmt::BreakStmtClass:
3962 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003963
3964 case Stmt::LabelStmtClass:
3965 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3966
3967 case Stmt::AttributedStmtClass:
3968 // As a general principle, C++11 attributes can be ignored without
3969 // any semantic impact.
3970 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3971 Case);
3972
3973 case Stmt::CaseStmtClass:
3974 case Stmt::DefaultStmtClass:
3975 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003976 }
3977}
3978
Richard Smithcc36f692011-12-22 02:22:31 +00003979/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3980/// default constructor. If so, we'll fold it whether or not it's marked as
3981/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3982/// so we need special handling.
3983static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003984 const CXXConstructorDecl *CD,
3985 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003986 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3987 return false;
3988
Richard Smith66e05fe2012-01-18 05:21:49 +00003989 // Value-initialization does not call a trivial default constructor, so such a
3990 // call is a core constant expression whether or not the constructor is
3991 // constexpr.
3992 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003993 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003994 // FIXME: If DiagDecl is an implicitly-declared special member function,
3995 // we should be much more explicit about why it's not constexpr.
3996 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3997 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3998 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003999 } else {
4000 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4001 }
4002 }
4003 return true;
4004}
4005
Richard Smith357362d2011-12-13 06:39:58 +00004006/// CheckConstexprFunction - Check that a function can be called in a constant
4007/// expression.
4008static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4009 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004010 const FunctionDecl *Definition,
4011 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004012 // Potential constant expressions can contain calls to declared, but not yet
4013 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004014 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004015 Declaration->isConstexpr())
4016 return false;
4017
Richard Smith0838f3a2013-05-14 05:18:44 +00004018 // Bail out with no diagnostic if the function declaration itself is invalid.
4019 // We will have produced a relevant diagnostic while parsing it.
4020 if (Declaration->isInvalidDecl())
4021 return false;
4022
Richard Smith357362d2011-12-13 06:39:58 +00004023 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004024 if (Definition && Definition->isConstexpr() &&
4025 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004026 return true;
4027
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004028 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004029 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Faisal Valie690b7a2016-07-02 22:34:24 +00004030
Richard Smith5179eb72016-06-28 19:03:57 +00004031 // If this function is not constexpr because it is an inherited
4032 // non-constexpr constructor, diagnose that directly.
4033 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4034 if (CD && CD->isInheritingConstructor()) {
4035 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4036 if (!Inherited->isConstexpr())
4037 DiagDecl = CD = Inherited;
4038 }
4039
4040 // FIXME: If DiagDecl is an implicitly-declared special member function
4041 // or an inheriting constructor, we should be much more explicit about why
4042 // it's not constexpr.
4043 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004044 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004045 << CD->getInheritedConstructor().getConstructor()->getParent();
4046 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004047 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004048 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004049 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4050 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004051 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004052 }
4053 return false;
4054}
4055
Richard Smithbe6dd812014-11-19 21:27:17 +00004056/// Determine if a class has any fields that might need to be copied by a
4057/// trivial copy or move operation.
4058static bool hasFields(const CXXRecordDecl *RD) {
4059 if (!RD || RD->isEmpty())
4060 return false;
4061 for (auto *FD : RD->fields()) {
4062 if (FD->isUnnamedBitfield())
4063 continue;
4064 return true;
4065 }
4066 for (auto &Base : RD->bases())
4067 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4068 return true;
4069 return false;
4070}
4071
Richard Smithd62306a2011-11-10 06:34:14 +00004072namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004073typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004074}
4075
4076/// EvaluateArgs - Evaluate the arguments to a function call.
4077static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4078 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004079 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004080 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004081 I != E; ++I) {
4082 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4083 // If we're checking for a potential constant expression, evaluate all
4084 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004085 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004086 return false;
4087 Success = false;
4088 }
4089 }
4090 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004091}
4092
Richard Smith254a73d2011-10-28 22:34:42 +00004093/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004094static bool HandleFunctionCall(SourceLocation CallLoc,
4095 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004096 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004097 EvalInfo &Info, APValue &Result,
4098 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004099 ArgVector ArgValues(Args.size());
4100 if (!EvaluateArgs(Args, ArgValues, Info))
4101 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004102
Richard Smith253c2a32012-01-27 01:14:48 +00004103 if (!Info.CheckCallLimit(CallLoc))
4104 return false;
4105
4106 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004107
4108 // For a trivial copy or move assignment, perform an APValue copy. This is
4109 // essential for unions, where the operations performed by the assignment
4110 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004111 //
4112 // Skip this for non-union classes with no fields; in that case, the defaulted
4113 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004114 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004115 if (MD && MD->isDefaulted() &&
4116 (MD->getParent()->isUnion() ||
4117 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004118 assert(This &&
4119 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4120 LValue RHS;
4121 RHS.setFrom(Info.Ctx, ArgValues[0]);
4122 APValue RHSValue;
4123 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4124 RHS, RHSValue))
4125 return false;
4126 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4127 RHSValue))
4128 return false;
4129 This->moveInto(Result);
4130 return true;
4131 }
4132
Richard Smith52a980a2015-08-28 02:43:42 +00004133 StmtResult Ret = {Result, ResultSlot};
4134 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004135 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004136 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004137 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004138 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004139 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004140 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004141}
4142
Richard Smithd62306a2011-11-10 06:34:14 +00004143/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004144static bool HandleConstructorCall(const Expr *E, const LValue &This,
4145 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004146 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004147 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004148 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004149 if (!Info.CheckCallLimit(CallLoc))
4150 return false;
4151
Richard Smith3607ffe2012-02-13 03:54:03 +00004152 const CXXRecordDecl *RD = Definition->getParent();
4153 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004154 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004155 return false;
4156 }
4157
Richard Smith5179eb72016-06-28 19:03:57 +00004158 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004159
Richard Smith52a980a2015-08-28 02:43:42 +00004160 // FIXME: Creating an APValue just to hold a nonexistent return value is
4161 // wasteful.
4162 APValue RetVal;
4163 StmtResult Ret = {RetVal, nullptr};
4164
Richard Smith5179eb72016-06-28 19:03:57 +00004165 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004166 if (Definition->isDelegatingConstructor()) {
4167 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004168 {
4169 FullExpressionRAII InitScope(Info);
4170 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4171 return false;
4172 }
Richard Smith52a980a2015-08-28 02:43:42 +00004173 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004174 }
4175
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004176 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004177 // essential for unions (or classes with anonymous union members), where the
4178 // operations performed by the constructor cannot be represented by
4179 // ctor-initializers.
4180 //
4181 // Skip this for empty non-union classes; we should not perform an
4182 // lvalue-to-rvalue conversion on them because their copy constructor does not
4183 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004184 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004185 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004186 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004187 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004188 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004189 return handleLValueToRValueConversion(
4190 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4191 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004192 }
4193
4194 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004195 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004196 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004197 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004198
John McCalld7bca762012-05-01 00:38:49 +00004199 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004200 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4201
Richard Smith08d6a2c2013-07-24 07:11:57 +00004202 // A scope for temporaries lifetime-extended by reference members.
4203 BlockScopeRAII LifetimeExtendedScope(Info);
4204
Richard Smith253c2a32012-01-27 01:14:48 +00004205 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004206 unsigned BasesSeen = 0;
4207#ifndef NDEBUG
4208 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4209#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004210 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004211 LValue Subobject = This;
4212 APValue *Value = &Result;
4213
4214 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004215 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004216 if (I->isBaseInitializer()) {
4217 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004218#ifndef NDEBUG
4219 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004220 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004221 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4222 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4223 "base class initializers not in expected order");
4224 ++BaseIt;
4225#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004226 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004227 BaseType->getAsCXXRecordDecl(), &Layout))
4228 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004229 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004230 } else if ((FD = I->getMember())) {
4231 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004232 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004233 if (RD->isUnion()) {
4234 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004235 Value = &Result.getUnionValue();
4236 } else {
4237 Value = &Result.getStructField(FD->getFieldIndex());
4238 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004239 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004240 // Walk the indirect field decl's chain to find the object to initialize,
4241 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004242 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004243 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004244 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4245 // Switch the union field if it differs. This happens if we had
4246 // preceding zero-initialization, and we're now initializing a union
4247 // subobject other than the first.
4248 // FIXME: In this case, the values of the other subobjects are
4249 // specified, since zero-initialization sets all padding bits to zero.
4250 if (Value->isUninit() ||
4251 (Value->isUnion() && Value->getUnionField() != FD)) {
4252 if (CD->isUnion())
4253 *Value = APValue(FD);
4254 else
4255 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004256 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004257 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004258 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004259 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004260 if (CD->isUnion())
4261 Value = &Value->getUnionValue();
4262 else
4263 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004264 }
Richard Smithd62306a2011-11-10 06:34:14 +00004265 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004266 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004267 }
Richard Smith253c2a32012-01-27 01:14:48 +00004268
Richard Smith08d6a2c2013-07-24 07:11:57 +00004269 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004270 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4271 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004272 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004273 // If we're checking for a potential constant expression, evaluate all
4274 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004275 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004276 return false;
4277 Success = false;
4278 }
Richard Smithd62306a2011-11-10 06:34:14 +00004279 }
4280
Richard Smithd9f663b2013-04-22 15:31:51 +00004281 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004282 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004283}
4284
Richard Smith5179eb72016-06-28 19:03:57 +00004285static bool HandleConstructorCall(const Expr *E, const LValue &This,
4286 ArrayRef<const Expr*> Args,
4287 const CXXConstructorDecl *Definition,
4288 EvalInfo &Info, APValue &Result) {
4289 ArgVector ArgValues(Args.size());
4290 if (!EvaluateArgs(Args, ArgValues, Info))
4291 return false;
4292
4293 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4294 Info, Result);
4295}
4296
Eli Friedman9a156e52008-11-12 09:44:48 +00004297//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004298// Generic Evaluation
4299//===----------------------------------------------------------------------===//
4300namespace {
4301
Aaron Ballman68af21c2014-01-03 19:26:43 +00004302template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004303class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004304 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004305private:
Richard Smith52a980a2015-08-28 02:43:42 +00004306 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004307 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004308 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004309 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004310 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004311 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004312 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004313
Richard Smith17100ba2012-02-16 02:46:34 +00004314 // Check whether a conditional operator with a non-constant condition is a
4315 // potential constant expression. If neither arm is a potential constant
4316 // expression, then the conditional operator is not either.
4317 template<typename ConditionalOperator>
4318 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004319 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004320
4321 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004322 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004323 {
Richard Smith17100ba2012-02-16 02:46:34 +00004324 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004325 StmtVisitorTy::Visit(E->getFalseExpr());
4326 if (Diag.empty())
4327 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004328 }
Richard Smith17100ba2012-02-16 02:46:34 +00004329
George Burgess IV8c892b52016-05-25 22:31:54 +00004330 {
4331 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004332 Diag.clear();
4333 StmtVisitorTy::Visit(E->getTrueExpr());
4334 if (Diag.empty())
4335 return;
4336 }
4337
4338 Error(E, diag::note_constexpr_conditional_never_const);
4339 }
4340
4341
4342 template<typename ConditionalOperator>
4343 bool HandleConditionalOperator(const ConditionalOperator *E) {
4344 bool BoolResult;
4345 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004346 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004347 CheckPotentialConstantConditional(E);
4348 return false;
4349 }
4350
4351 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4352 return StmtVisitorTy::Visit(EvalExpr);
4353 }
4354
Peter Collingbournee9200682011-05-13 03:29:01 +00004355protected:
4356 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004357 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004358 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4359
Richard Smith92b1ce02011-12-12 09:28:41 +00004360 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004361 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004362 }
4363
Aaron Ballman68af21c2014-01-03 19:26:43 +00004364 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004365
4366public:
4367 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4368
4369 EvalInfo &getEvalInfo() { return Info; }
4370
Richard Smithf57d8cb2011-12-09 22:58:01 +00004371 /// Report an evaluation error. This should only be called when an error is
4372 /// first discovered. When propagating an error, just return false.
4373 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004374 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004375 return false;
4376 }
4377 bool Error(const Expr *E) {
4378 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4379 }
4380
Aaron Ballman68af21c2014-01-03 19:26:43 +00004381 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004382 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004383 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004384 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004385 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004386 }
4387
Aaron Ballman68af21c2014-01-03 19:26:43 +00004388 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004389 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004390 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004391 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004392 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004393 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004394 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004395 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004396 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004397 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004398 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004399 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004400 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004401 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004402 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004403 // The initializer may not have been parsed yet, or might be erroneous.
4404 if (!E->getExpr())
4405 return Error(E);
4406 return StmtVisitorTy::Visit(E->getExpr());
4407 }
Richard Smith5894a912011-12-19 22:12:41 +00004408 // We cannot create any objects for which cleanups are required, so there is
4409 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004410 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004411 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004412
Aaron Ballman68af21c2014-01-03 19:26:43 +00004413 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004414 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4415 return static_cast<Derived*>(this)->VisitCastExpr(E);
4416 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004417 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004418 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4419 return static_cast<Derived*>(this)->VisitCastExpr(E);
4420 }
4421
Aaron Ballman68af21c2014-01-03 19:26:43 +00004422 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004423 switch (E->getOpcode()) {
4424 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004425 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004426
4427 case BO_Comma:
4428 VisitIgnoredValue(E->getLHS());
4429 return StmtVisitorTy::Visit(E->getRHS());
4430
4431 case BO_PtrMemD:
4432 case BO_PtrMemI: {
4433 LValue Obj;
4434 if (!HandleMemberPointerAccess(Info, E, Obj))
4435 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004436 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004437 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004438 return false;
4439 return DerivedSuccess(Result, E);
4440 }
4441 }
4442 }
4443
Aaron Ballman68af21c2014-01-03 19:26:43 +00004444 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004445 // Evaluate and cache the common expression. We treat it as a temporary,
4446 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004447 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004448 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004449 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004450
Richard Smith17100ba2012-02-16 02:46:34 +00004451 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004452 }
4453
Aaron Ballman68af21c2014-01-03 19:26:43 +00004454 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004455 bool IsBcpCall = false;
4456 // If the condition (ignoring parens) is a __builtin_constant_p call,
4457 // the result is a constant expression if it can be folded without
4458 // side-effects. This is an important GNU extension. See GCC PR38377
4459 // for discussion.
4460 if (const CallExpr *CallCE =
4461 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004462 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004463 IsBcpCall = true;
4464
4465 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4466 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004467 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004468 return false;
4469
Richard Smith6d4c6582013-11-05 22:18:15 +00004470 FoldConstant Fold(Info, IsBcpCall);
4471 if (!HandleConditionalOperator(E)) {
4472 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004473 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004474 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004475
4476 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004477 }
4478
Aaron Ballman68af21c2014-01-03 19:26:43 +00004479 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004480 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4481 return DerivedSuccess(*Value, E);
4482
4483 const Expr *Source = E->getSourceExpr();
4484 if (!Source)
4485 return Error(E);
4486 if (Source == E) { // sanity checking.
4487 assert(0 && "OpaqueValueExpr recursively refers to itself");
4488 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004489 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004490 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004491 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004492
Aaron Ballman68af21c2014-01-03 19:26:43 +00004493 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004494 APValue Result;
4495 if (!handleCallExpr(E, Result, nullptr))
4496 return false;
4497 return DerivedSuccess(Result, E);
4498 }
4499
4500 bool handleCallExpr(const CallExpr *E, APValue &Result,
4501 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004502 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004503 QualType CalleeType = Callee->getType();
4504
Craig Topper36250ad2014-05-12 05:36:57 +00004505 const FunctionDecl *FD = nullptr;
4506 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004507 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004508 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004509
Richard Smithe97cbd72011-11-11 04:05:33 +00004510 // Extract function decl and 'this' pointer from the callee.
4511 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004512 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004513 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4514 // Explicit bound member calls, such as x.f() or p->g();
4515 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004516 return false;
4517 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004518 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004519 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004520 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4521 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004522 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4523 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004524 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004525 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004526 return Error(Callee);
4527
4528 FD = dyn_cast<FunctionDecl>(Member);
4529 if (!FD)
4530 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004531 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004532 LValue Call;
4533 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004534 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004535
Richard Smitha8105bc2012-01-06 16:39:00 +00004536 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004537 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004538 FD = dyn_cast_or_null<FunctionDecl>(
4539 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004540 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004541 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004542
4543 // Overloaded operator calls to member functions are represented as normal
4544 // calls with '*this' as the first argument.
4545 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4546 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004547 // FIXME: When selecting an implicit conversion for an overloaded
4548 // operator delete, we sometimes try to evaluate calls to conversion
4549 // operators without a 'this' parameter!
4550 if (Args.empty())
4551 return Error(E);
4552
Richard Smithe97cbd72011-11-11 04:05:33 +00004553 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4554 return false;
4555 This = &ThisVal;
4556 Args = Args.slice(1);
4557 }
4558
4559 // Don't call function pointers which have been cast to some other type.
Richard Smithdfe85e22016-12-15 02:35:39 +00004560 // Per DR (no number yet), the caller and callee can differ in noexcept.
4561 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4562 CalleeType->getPointeeType(), FD->getType())) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004563 return Error(E);
Richard Smithdfe85e22016-12-15 02:35:39 +00004564 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004565 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004566 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004567
Richard Smith47b34932012-02-01 02:39:43 +00004568 if (This && !This->checkSubobject(Info, E, CSK_This))
4569 return false;
4570
Richard Smith3607ffe2012-02-13 03:54:03 +00004571 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4572 // calls to such functions in constant expressions.
4573 if (This && !HasQualifier &&
4574 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4575 return Error(E, diag::note_constexpr_virtual_call);
4576
Craig Topper36250ad2014-05-12 05:36:57 +00004577 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004578 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004579
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004580 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004581 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4582 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004583 return false;
4584
Richard Smith52a980a2015-08-28 02:43:42 +00004585 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004586 }
4587
Aaron Ballman68af21c2014-01-03 19:26:43 +00004588 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004589 return StmtVisitorTy::Visit(E->getInitializer());
4590 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004591 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004592 if (E->getNumInits() == 0)
4593 return DerivedZeroInitialization(E);
4594 if (E->getNumInits() == 1)
4595 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004596 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004597 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004598 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004599 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004600 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004601 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004602 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004603 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004604 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004605 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004606 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004607
Richard Smithd62306a2011-11-10 06:34:14 +00004608 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004609 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004610 assert(!E->isArrow() && "missing call to bound member function?");
4611
Richard Smith2e312c82012-03-03 22:46:17 +00004612 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004613 if (!Evaluate(Val, Info, E->getBase()))
4614 return false;
4615
4616 QualType BaseTy = E->getBase()->getType();
4617
4618 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004619 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004620 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004621 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004622 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4623
Richard Smith3229b742013-05-05 21:17:10 +00004624 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004625 SubobjectDesignator Designator(BaseTy);
4626 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004627
Richard Smith3229b742013-05-05 21:17:10 +00004628 APValue Result;
4629 return extractSubobject(Info, E, Obj, Designator, Result) &&
4630 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004631 }
4632
Aaron Ballman68af21c2014-01-03 19:26:43 +00004633 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004634 switch (E->getCastKind()) {
4635 default:
4636 break;
4637
Richard Smitha23ab512013-05-23 00:30:41 +00004638 case CK_AtomicToNonAtomic: {
4639 APValue AtomicVal;
4640 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4641 return false;
4642 return DerivedSuccess(AtomicVal, E);
4643 }
4644
Richard Smith11562c52011-10-28 17:51:58 +00004645 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004646 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004647 return StmtVisitorTy::Visit(E->getSubExpr());
4648
4649 case CK_LValueToRValue: {
4650 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004651 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4652 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004653 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004654 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004655 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004656 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004657 return false;
4658 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004659 }
4660 }
4661
Richard Smithf57d8cb2011-12-09 22:58:01 +00004662 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004663 }
4664
Aaron Ballman68af21c2014-01-03 19:26:43 +00004665 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004666 return VisitUnaryPostIncDec(UO);
4667 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004668 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004669 return VisitUnaryPostIncDec(UO);
4670 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004671 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004672 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004673 return Error(UO);
4674
4675 LValue LVal;
4676 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4677 return false;
4678 APValue RVal;
4679 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4680 UO->isIncrementOp(), &RVal))
4681 return false;
4682 return DerivedSuccess(RVal, UO);
4683 }
4684
Aaron Ballman68af21c2014-01-03 19:26:43 +00004685 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004686 // We will have checked the full-expressions inside the statement expression
4687 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004688 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004689 return Error(E);
4690
Richard Smith08d6a2c2013-07-24 07:11:57 +00004691 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004692 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004693 if (CS->body_empty())
4694 return true;
4695
Richard Smith51f03172013-06-20 03:00:05 +00004696 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4697 BE = CS->body_end();
4698 /**/; ++BI) {
4699 if (BI + 1 == BE) {
4700 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4701 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004702 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004703 diag::note_constexpr_stmt_expr_unsupported);
4704 return false;
4705 }
4706 return this->Visit(FinalExpr);
4707 }
4708
4709 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004710 StmtResult Result = { ReturnValue, nullptr };
4711 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004712 if (ESR != ESR_Succeeded) {
4713 // FIXME: If the statement-expression terminated due to 'return',
4714 // 'break', or 'continue', it would be nice to propagate that to
4715 // the outer statement evaluation rather than bailing out.
4716 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004717 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004718 diag::note_constexpr_stmt_expr_unsupported);
4719 return false;
4720 }
4721 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004722
4723 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004724 }
4725
Richard Smith4a678122011-10-24 18:44:57 +00004726 /// Visit a value which is evaluated, but whose value is ignored.
4727 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004728 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004729 }
David Majnemere9807b22016-02-26 04:23:19 +00004730
4731 /// Potentially visit a MemberExpr's base expression.
4732 void VisitIgnoredBaseExpression(const Expr *E) {
4733 // While MSVC doesn't evaluate the base expression, it does diagnose the
4734 // presence of side-effecting behavior.
4735 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4736 return;
4737 VisitIgnoredValue(E);
4738 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004739};
4740
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004741}
Peter Collingbournee9200682011-05-13 03:29:01 +00004742
4743//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004744// Common base class for lvalue and temporary evaluation.
4745//===----------------------------------------------------------------------===//
4746namespace {
4747template<class Derived>
4748class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004749 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004750protected:
4751 LValue &Result;
4752 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004753 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004754
4755 bool Success(APValue::LValueBase B) {
4756 Result.set(B);
4757 return true;
4758 }
4759
4760public:
4761 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4762 ExprEvaluatorBaseTy(Info), Result(Result) {}
4763
Richard Smith2e312c82012-03-03 22:46:17 +00004764 bool Success(const APValue &V, const Expr *E) {
4765 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004766 return true;
4767 }
Richard Smith027bf112011-11-17 22:56:20 +00004768
Richard Smith027bf112011-11-17 22:56:20 +00004769 bool VisitMemberExpr(const MemberExpr *E) {
4770 // Handle non-static data members.
4771 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004772 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004773 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004774 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004775 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004776 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004777 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004778 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004779 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004780 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004781 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004782 BaseTy = E->getBase()->getType();
4783 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004784 if (!EvalOK) {
4785 if (!this->Info.allowInvalidBaseExpr())
4786 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004787 Result.setInvalid(E);
4788 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004789 }
Richard Smith027bf112011-11-17 22:56:20 +00004790
Richard Smith1b78b3d2012-01-25 22:15:11 +00004791 const ValueDecl *MD = E->getMemberDecl();
4792 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4793 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4794 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4795 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004796 if (!HandleLValueMember(this->Info, E, Result, FD))
4797 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004798 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004799 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4800 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004801 } else
4802 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004803
Richard Smith1b78b3d2012-01-25 22:15:11 +00004804 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004805 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004806 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004807 RefValue))
4808 return false;
4809 return Success(RefValue, E);
4810 }
4811 return true;
4812 }
4813
4814 bool VisitBinaryOperator(const BinaryOperator *E) {
4815 switch (E->getOpcode()) {
4816 default:
4817 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4818
4819 case BO_PtrMemD:
4820 case BO_PtrMemI:
4821 return HandleMemberPointerAccess(this->Info, E, Result);
4822 }
4823 }
4824
4825 bool VisitCastExpr(const CastExpr *E) {
4826 switch (E->getCastKind()) {
4827 default:
4828 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4829
4830 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004831 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004832 if (!this->Visit(E->getSubExpr()))
4833 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004834
4835 // Now figure out the necessary offset to add to the base LV to get from
4836 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004837 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4838 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004839 }
4840 }
4841};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004842}
Richard Smith027bf112011-11-17 22:56:20 +00004843
4844//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004845// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004846//
4847// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4848// function designators (in C), decl references to void objects (in C), and
4849// temporaries (if building with -Wno-address-of-temporary).
4850//
4851// LValue evaluation produces values comprising a base expression of one of the
4852// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004853// - Declarations
4854// * VarDecl
4855// * FunctionDecl
4856// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00004857// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00004858// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004859// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004860// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004861// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004862// * ObjCEncodeExpr
4863// * AddrLabelExpr
4864// * BlockExpr
4865// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004866// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004867// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004868// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004869// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4870// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004871// * A MaterializeTemporaryExpr that has static storage duration, with no
4872// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004873// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004874//===----------------------------------------------------------------------===//
4875namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004876class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004877 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004878public:
Richard Smith027bf112011-11-17 22:56:20 +00004879 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4880 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004881
Richard Smith11562c52011-10-28 17:51:58 +00004882 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004883 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004884
Peter Collingbournee9200682011-05-13 03:29:01 +00004885 bool VisitDeclRefExpr(const DeclRefExpr *E);
4886 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004887 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004888 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4889 bool VisitMemberExpr(const MemberExpr *E);
4890 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4891 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004892 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004893 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004894 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4895 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004896 bool VisitUnaryReal(const UnaryOperator *E);
4897 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004898 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4899 return VisitUnaryPreIncDec(UO);
4900 }
4901 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4902 return VisitUnaryPreIncDec(UO);
4903 }
Richard Smith3229b742013-05-05 21:17:10 +00004904 bool VisitBinAssign(const BinaryOperator *BO);
4905 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004906
Peter Collingbournee9200682011-05-13 03:29:01 +00004907 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004908 switch (E->getCastKind()) {
4909 default:
Richard Smith027bf112011-11-17 22:56:20 +00004910 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004911
Eli Friedmance3e02a2011-10-11 00:13:24 +00004912 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004913 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004914 if (!Visit(E->getSubExpr()))
4915 return false;
4916 Result.Designator.setInvalid();
4917 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004918
Richard Smith027bf112011-11-17 22:56:20 +00004919 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004920 if (!Visit(E->getSubExpr()))
4921 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004922 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004923 }
4924 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004925};
4926} // end anonymous namespace
4927
Richard Smith11562c52011-10-28 17:51:58 +00004928/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004929/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004930/// * function designators in C, and
4931/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004932/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004933static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4934 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004935 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004936 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004937}
4938
Peter Collingbournee9200682011-05-13 03:29:01 +00004939bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004940 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004941 return Success(FD);
4942 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004943 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00004944 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00004945 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00004946 return Error(E);
4947}
Richard Smith733237d2011-10-24 23:14:33 +00004948
Faisal Vali0528a312016-11-13 06:09:16 +00004949
Richard Smith11562c52011-10-28 17:51:58 +00004950bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004951 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00004952 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
4953 // Only if a local variable was declared in the function currently being
4954 // evaluated, do we expect to be able to find its value in the current
4955 // frame. (Otherwise it was likely declared in an enclosing context and
4956 // could either have a valid evaluatable value (for e.g. a constexpr
4957 // variable) or be ill-formed (and trigger an appropriate evaluation
4958 // diagnostic)).
4959 if (Info.CurrentCall->Callee &&
4960 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
4961 Frame = Info.CurrentCall;
4962 }
4963 }
Richard Smith3229b742013-05-05 21:17:10 +00004964
Richard Smithfec09922011-11-01 16:57:24 +00004965 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004966 if (Frame) {
4967 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004968 return true;
4969 }
Richard Smithce40ad62011-11-12 22:28:03 +00004970 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004971 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004972
Richard Smith3229b742013-05-05 21:17:10 +00004973 APValue *V;
4974 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004975 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004976 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004977 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00004978 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004979 return false;
4980 }
Richard Smith3229b742013-05-05 21:17:10 +00004981 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004982}
4983
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004984bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4985 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004986 // Walk through the expression to find the materialized temporary itself.
4987 SmallVector<const Expr *, 2> CommaLHSs;
4988 SmallVector<SubobjectAdjustment, 2> Adjustments;
4989 const Expr *Inner = E->GetTemporaryExpr()->
4990 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004991
Richard Smith84401042013-06-03 05:03:02 +00004992 // If we passed any comma operators, evaluate their LHSs.
4993 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4994 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4995 return false;
4996
Richard Smithe6c01442013-06-05 00:46:14 +00004997 // A materialized temporary with static storage duration can appear within the
4998 // result of a constant expression evaluation, so we need to preserve its
4999 // value for use outside this evaluation.
5000 APValue *Value;
5001 if (E->getStorageDuration() == SD_Static) {
5002 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005003 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005004 Result.set(E);
5005 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005006 Value = &Info.CurrentCall->
5007 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005008 Result.set(E, Info.CurrentCall->Index);
5009 }
5010
Richard Smithea4ad5d2013-06-06 08:19:16 +00005011 QualType Type = Inner->getType();
5012
Richard Smith84401042013-06-03 05:03:02 +00005013 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005014 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5015 (E->getStorageDuration() == SD_Static &&
5016 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5017 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005018 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005019 }
Richard Smith84401042013-06-03 05:03:02 +00005020
5021 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005022 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5023 --I;
5024 switch (Adjustments[I].Kind) {
5025 case SubobjectAdjustment::DerivedToBaseAdjustment:
5026 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5027 Type, Result))
5028 return false;
5029 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5030 break;
5031
5032 case SubobjectAdjustment::FieldAdjustment:
5033 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5034 return false;
5035 Type = Adjustments[I].Field->getType();
5036 break;
5037
5038 case SubobjectAdjustment::MemberPointerAdjustment:
5039 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5040 Adjustments[I].Ptr.RHS))
5041 return false;
5042 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5043 break;
5044 }
5045 }
5046
5047 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005048}
5049
Peter Collingbournee9200682011-05-13 03:29:01 +00005050bool
5051LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005052 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5053 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005054 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5055 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005056 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005057}
5058
Richard Smith6e525142011-12-27 12:18:28 +00005059bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005060 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005061 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005062
Faisal Valie690b7a2016-07-02 22:34:24 +00005063 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005064 << E->getExprOperand()->getType()
5065 << E->getExprOperand()->getSourceRange();
5066 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005067}
5068
Francois Pichet0066db92012-04-16 04:08:35 +00005069bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5070 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005071}
Francois Pichet0066db92012-04-16 04:08:35 +00005072
Peter Collingbournee9200682011-05-13 03:29:01 +00005073bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005074 // Handle static data members.
5075 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005076 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005077 return VisitVarDecl(E, VD);
5078 }
5079
Richard Smith254a73d2011-10-28 22:34:42 +00005080 // Handle static member functions.
5081 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5082 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005083 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005084 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005085 }
5086 }
5087
Richard Smithd62306a2011-11-10 06:34:14 +00005088 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005089 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005090}
5091
Peter Collingbournee9200682011-05-13 03:29:01 +00005092bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005093 // FIXME: Deal with vectors as array subscript bases.
5094 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005095 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005096
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005097 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00005098 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005099
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005100 APSInt Index;
5101 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005102 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005103
Richard Smith861b5b52013-05-07 23:34:45 +00005104 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
5105 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005106}
Eli Friedman9a156e52008-11-12 09:44:48 +00005107
Peter Collingbournee9200682011-05-13 03:29:01 +00005108bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00005109 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005110}
5111
Richard Smith66c96992012-02-18 22:04:06 +00005112bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5113 if (!Visit(E->getSubExpr()))
5114 return false;
5115 // __real is a no-op on scalar lvalues.
5116 if (E->getSubExpr()->getType()->isAnyComplexType())
5117 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5118 return true;
5119}
5120
5121bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5122 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5123 "lvalue __imag__ on scalar?");
5124 if (!Visit(E->getSubExpr()))
5125 return false;
5126 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5127 return true;
5128}
5129
Richard Smith243ef902013-05-05 23:31:59 +00005130bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005131 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005132 return Error(UO);
5133
5134 if (!this->Visit(UO->getSubExpr()))
5135 return false;
5136
Richard Smith243ef902013-05-05 23:31:59 +00005137 return handleIncDec(
5138 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005139 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005140}
5141
5142bool LValueExprEvaluator::VisitCompoundAssignOperator(
5143 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005144 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005145 return Error(CAO);
5146
Richard Smith3229b742013-05-05 21:17:10 +00005147 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005148
5149 // The overall lvalue result is the result of evaluating the LHS.
5150 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005151 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005152 Evaluate(RHS, this->Info, CAO->getRHS());
5153 return false;
5154 }
5155
Richard Smith3229b742013-05-05 21:17:10 +00005156 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5157 return false;
5158
Richard Smith43e77732013-05-07 04:50:00 +00005159 return handleCompoundAssignment(
5160 this->Info, CAO,
5161 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5162 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005163}
5164
5165bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005166 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005167 return Error(E);
5168
Richard Smith3229b742013-05-05 21:17:10 +00005169 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005170
5171 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005172 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005173 Evaluate(NewVal, this->Info, E->getRHS());
5174 return false;
5175 }
5176
Richard Smith3229b742013-05-05 21:17:10 +00005177 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5178 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005179
5180 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005181 NewVal);
5182}
5183
Eli Friedman9a156e52008-11-12 09:44:48 +00005184//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005185// Pointer Evaluation
5186//===----------------------------------------------------------------------===//
5187
George Burgess IVa7470272016-12-20 01:05:42 +00005188/// \brief Attempts to compute the number of bytes available at the pointer
5189/// returned by a function with the alloc_size attribute. Returns true if we
5190/// were successful. Places an unsigned number into `Result`.
5191///
5192/// This expects the given CallExpr to be a call to a function with an
5193/// alloc_size attribute.
5194static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5195 const CallExpr *Call,
5196 llvm::APInt &Result) {
5197 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5198
5199 // alloc_size args are 1-indexed, 0 means not present.
5200 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5201 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5202 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5203 if (Call->getNumArgs() <= SizeArgNo)
5204 return false;
5205
5206 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5207 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5208 return false;
5209 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5210 return false;
5211 Into = Into.zextOrSelf(BitsInSizeT);
5212 return true;
5213 };
5214
5215 APSInt SizeOfElem;
5216 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5217 return false;
5218
5219 if (!AllocSize->getNumElemsParam()) {
5220 Result = std::move(SizeOfElem);
5221 return true;
5222 }
5223
5224 APSInt NumberOfElems;
5225 // Argument numbers start at 1
5226 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5227 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5228 return false;
5229
5230 bool Overflow;
5231 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5232 if (Overflow)
5233 return false;
5234
5235 Result = std::move(BytesAvailable);
5236 return true;
5237}
5238
5239/// \brief Convenience function. LVal's base must be a call to an alloc_size
5240/// function.
5241static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5242 const LValue &LVal,
5243 llvm::APInt &Result) {
5244 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5245 "Can't get the size of a non alloc_size function");
5246 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5247 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5248 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5249}
5250
5251/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5252/// a function with the alloc_size attribute. If it was possible to do so, this
5253/// function will return true, make Result's Base point to said function call,
5254/// and mark Result's Base as invalid.
5255static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5256 LValue &Result) {
5257 if (!Info.allowInvalidBaseExpr() || Base.isNull())
5258 return false;
5259
5260 // Because we do no form of static analysis, we only support const variables.
5261 //
5262 // Additionally, we can't support parameters, nor can we support static
5263 // variables (in the latter case, use-before-assign isn't UB; in the former,
5264 // we have no clue what they'll be assigned to).
5265 const auto *VD =
5266 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5267 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5268 return false;
5269
5270 const Expr *Init = VD->getAnyInitializer();
5271 if (!Init)
5272 return false;
5273
5274 const Expr *E = Init->IgnoreParens();
5275 if (!tryUnwrapAllocSizeCall(E))
5276 return false;
5277
5278 // Store E instead of E unwrapped so that the type of the LValue's base is
5279 // what the user wanted.
5280 Result.setInvalid(E);
5281
5282 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5283 Result.addUnsizedArray(Info, Pointee);
5284 return true;
5285}
5286
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005287namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005288class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005289 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005290 LValue &Result;
5291
Peter Collingbournee9200682011-05-13 03:29:01 +00005292 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005293 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005294 return true;
5295 }
George Burgess IVa7470272016-12-20 01:05:42 +00005296
5297 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005298public:
Mike Stump11289f42009-09-09 15:08:12 +00005299
John McCall45d55e42010-05-07 21:00:08 +00005300 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005301 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005302
Richard Smith2e312c82012-03-03 22:46:17 +00005303 bool Success(const APValue &V, const Expr *E) {
5304 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005305 return true;
5306 }
Richard Smithfddd3842011-12-30 21:15:51 +00005307 bool ZeroInitialization(const Expr *E) {
Yaxun Liu402804b2016-12-15 08:09:08 +00005308 auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
5309 Result.set((Expr*)nullptr, 0, false, true, Offset);
5310 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005311 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005312
John McCall45d55e42010-05-07 21:00:08 +00005313 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005314 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005315 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005316 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005317 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00005318 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005319 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005320 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005321 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005322 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005323 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005324 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005325 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005326 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005327 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005328 }
Richard Smithd62306a2011-11-10 06:34:14 +00005329 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005330 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005331 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005332 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005333 if (!Info.CurrentCall->This) {
5334 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005335 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005336 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005337 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005338 return false;
5339 }
Richard Smithd62306a2011-11-10 06:34:14 +00005340 Result = *Info.CurrentCall->This;
5341 return true;
5342 }
John McCallc07a0c72011-02-17 10:25:35 +00005343
Eli Friedman449fe542009-03-23 04:56:01 +00005344 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005345};
Chris Lattner05706e882008-07-11 18:11:29 +00005346} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005347
John McCall45d55e42010-05-07 21:00:08 +00005348static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005349 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00005350 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005351}
5352
John McCall45d55e42010-05-07 21:00:08 +00005353bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005354 if (E->getOpcode() != BO_Add &&
5355 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005356 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005357
Chris Lattner05706e882008-07-11 18:11:29 +00005358 const Expr *PExp = E->getLHS();
5359 const Expr *IExp = E->getRHS();
5360 if (IExp->getType()->isPointerType())
5361 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005362
Richard Smith253c2a32012-01-27 01:14:48 +00005363 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00005364 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005365 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005366
John McCall45d55e42010-05-07 21:00:08 +00005367 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005368 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005369 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005370
5371 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00005372 if (E->getOpcode() == BO_Sub)
5373 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00005374
Ted Kremenek28831752012-08-23 20:46:57 +00005375 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00005376 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5377 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00005378}
Eli Friedman9a156e52008-11-12 09:44:48 +00005379
John McCall45d55e42010-05-07 21:00:08 +00005380bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5381 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005382}
Mike Stump11289f42009-09-09 15:08:12 +00005383
Peter Collingbournee9200682011-05-13 03:29:01 +00005384bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5385 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005386
Eli Friedman847a2bc2009-12-27 05:43:15 +00005387 switch (E->getCastKind()) {
5388 default:
5389 break;
5390
John McCalle3027922010-08-25 11:45:40 +00005391 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005392 case CK_CPointerToObjCPointerCast:
5393 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005394 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005395 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005396 if (!Visit(SubExpr))
5397 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005398 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5399 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5400 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005401 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005402 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005403 if (SubExpr->getType()->isVoidPointerType())
5404 CCEDiag(E, diag::note_constexpr_invalid_cast)
5405 << 3 << SubExpr->getType();
5406 else
5407 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5408 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005409 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5410 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005411 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005412
Anders Carlsson18275092010-10-31 20:41:46 +00005413 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005414 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00005415 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00005416 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005417 if (!Result.Base && Result.Offset.isZero())
5418 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005419
Richard Smithd62306a2011-11-10 06:34:14 +00005420 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005421 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005422 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5423 castAs<PointerType>()->getPointeeType(),
5424 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005425
Richard Smith027bf112011-11-17 22:56:20 +00005426 case CK_BaseToDerived:
5427 if (!Visit(E->getSubExpr()))
5428 return false;
5429 if (!Result.Base && Result.Offset.isZero())
5430 return true;
5431 return HandleBaseToDerivedCast(Info, E, Result);
5432
Richard Smith0b0a0b62011-10-29 20:57:55 +00005433 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005434 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005435 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005436
John McCalle3027922010-08-25 11:45:40 +00005437 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005438 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5439
Richard Smith2e312c82012-03-03 22:46:17 +00005440 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005441 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005442 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005443
John McCall45d55e42010-05-07 21:00:08 +00005444 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005445 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5446 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005447 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005448 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005449 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005450 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005451 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005452 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005453 return true;
5454 } else {
5455 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005456 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005457 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005458 }
5459 }
John McCalle3027922010-08-25 11:45:40 +00005460 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005461 if (SubExpr->isGLValue()) {
5462 if (!EvaluateLValue(SubExpr, Result, Info))
5463 return false;
5464 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005465 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005466 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005467 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005468 return false;
5469 }
Richard Smith96e0c102011-11-04 02:25:55 +00005470 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005471 if (const ConstantArrayType *CAT
5472 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5473 Result.addArray(Info, E, CAT);
5474 else
5475 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005476 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005477
John McCalle3027922010-08-25 11:45:40 +00005478 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005479 return EvaluateLValue(SubExpr, Result, Info);
George Burgess IVa7470272016-12-20 01:05:42 +00005480
5481 case CK_LValueToRValue: {
5482 LValue LVal;
5483 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5484 return false;
5485
5486 APValue RVal;
5487 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5488 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5489 LVal, RVal))
5490 return evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5491 return Success(RVal, E);
5492 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005493 }
5494
Richard Smith11562c52011-10-28 17:51:58 +00005495 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005496}
Chris Lattner05706e882008-07-11 18:11:29 +00005497
Hal Finkel0dd05d42014-10-03 17:18:37 +00005498static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5499 // C++ [expr.alignof]p3:
5500 // When alignof is applied to a reference type, the result is the
5501 // alignment of the referenced type.
5502 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5503 T = Ref->getPointeeType();
5504
5505 // __alignof is defined to return the preferred alignment.
5506 return Info.Ctx.toCharUnitsFromBits(
5507 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5508}
5509
5510static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5511 E = E->IgnoreParens();
5512
5513 // The kinds of expressions that we have special-case logic here for
5514 // should be kept up to date with the special checks for those
5515 // expressions in Sema.
5516
5517 // alignof decl is always accepted, even if it doesn't make sense: we default
5518 // to 1 in those cases.
5519 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5520 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5521 /*RefAsPointee*/true);
5522
5523 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5524 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5525 /*RefAsPointee*/true);
5526
5527 return GetAlignOfType(Info, E->getType());
5528}
5529
George Burgess IVa7470272016-12-20 01:05:42 +00005530// To be clear: this happily visits unsupported builtins. Better name welcomed.
5531bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5532 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5533 return true;
5534
5535 if (!(Info.allowInvalidBaseExpr() && getAllocSizeAttr(E)))
5536 return false;
5537
5538 Result.setInvalid(E);
5539 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5540 Result.addUnsizedArray(Info, PointeeTy);
5541 return true;
5542}
5543
Peter Collingbournee9200682011-05-13 03:29:01 +00005544bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005545 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005546 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005547
Richard Smith6328cbd2016-11-16 00:57:23 +00005548 if (unsigned BuiltinOp = E->getBuiltinCallee())
5549 return VisitBuiltinCallExpr(E, BuiltinOp);
5550
George Burgess IVa7470272016-12-20 01:05:42 +00005551 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005552}
5553
5554bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5555 unsigned BuiltinOp) {
5556 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005557 case Builtin::BI__builtin_addressof:
5558 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005559 case Builtin::BI__builtin_assume_aligned: {
5560 // We need to be very careful here because: if the pointer does not have the
5561 // asserted alignment, then the behavior is undefined, and undefined
5562 // behavior is non-constant.
5563 if (!EvaluatePointer(E->getArg(0), Result, Info))
5564 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005565
Hal Finkel0dd05d42014-10-03 17:18:37 +00005566 LValue OffsetResult(Result);
5567 APSInt Alignment;
5568 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5569 return false;
5570 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5571
5572 if (E->getNumArgs() > 2) {
5573 APSInt Offset;
5574 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5575 return false;
5576
5577 int64_t AdditionalOffset = -getExtValue(Offset);
5578 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5579 }
5580
5581 // If there is a base object, then it must have the correct alignment.
5582 if (OffsetResult.Base) {
5583 CharUnits BaseAlignment;
5584 if (const ValueDecl *VD =
5585 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5586 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5587 } else {
5588 BaseAlignment =
5589 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5590 }
5591
5592 if (BaseAlignment < Align) {
5593 Result.Designator.setInvalid();
Yaron Kerene0bcdd42016-10-08 06:45:10 +00005594 // FIXME: Quantities here cast to integers because the plural modifier
5595 // does not work on APSInts yet.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005596 CCEDiag(E->getArg(0),
5597 diag::note_constexpr_baa_insufficient_alignment) << 0
5598 << (int) BaseAlignment.getQuantity()
5599 << (unsigned) getExtValue(Alignment);
5600 return false;
5601 }
5602 }
5603
5604 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005605 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005606 Result.Designator.setInvalid();
5607 APSInt Offset(64, false);
5608 Offset = OffsetResult.Offset.getQuantity();
5609
5610 if (OffsetResult.Base)
5611 CCEDiag(E->getArg(0),
5612 diag::note_constexpr_baa_insufficient_alignment) << 1
5613 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5614 else
5615 CCEDiag(E->getArg(0),
5616 diag::note_constexpr_baa_value_insufficient_alignment)
5617 << Offset << (unsigned) getExtValue(Alignment);
5618
5619 return false;
5620 }
5621
5622 return true;
5623 }
Richard Smithe9507952016-11-12 01:39:56 +00005624
5625 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005626 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005627 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005628 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005629 if (Info.getLangOpts().CPlusPlus11)
5630 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5631 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005632 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005633 else
5634 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5635 // Fall through.
5636 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005637 case Builtin::BI__builtin_wcschr:
5638 case Builtin::BI__builtin_memchr:
5639 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005640 if (!Visit(E->getArg(0)))
5641 return false;
5642 APSInt Desired;
5643 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5644 return false;
5645 uint64_t MaxLength = uint64_t(-1);
5646 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005647 BuiltinOp != Builtin::BIwcschr &&
5648 BuiltinOp != Builtin::BI__builtin_strchr &&
5649 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005650 APSInt N;
5651 if (!EvaluateInteger(E->getArg(2), N, Info))
5652 return false;
5653 MaxLength = N.getExtValue();
5654 }
5655
Richard Smith8110c9d2016-11-29 19:45:17 +00005656 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005657
Richard Smith8110c9d2016-11-29 19:45:17 +00005658 // Figure out what value we're actually looking for (after converting to
5659 // the corresponding unsigned type if necessary).
5660 uint64_t DesiredVal;
5661 bool StopAtNull = false;
5662 switch (BuiltinOp) {
5663 case Builtin::BIstrchr:
5664 case Builtin::BI__builtin_strchr:
5665 // strchr compares directly to the passed integer, and therefore
5666 // always fails if given an int that is not a char.
5667 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5668 E->getArg(1)->getType(),
5669 Desired),
5670 Desired))
5671 return ZeroInitialization(E);
5672 StopAtNull = true;
5673 // Fall through.
5674 case Builtin::BImemchr:
5675 case Builtin::BI__builtin_memchr:
5676 // memchr compares by converting both sides to unsigned char. That's also
5677 // correct for strchr if we get this far (to cope with plain char being
5678 // unsigned in the strchr case).
5679 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5680 break;
Richard Smithe9507952016-11-12 01:39:56 +00005681
Richard Smith8110c9d2016-11-29 19:45:17 +00005682 case Builtin::BIwcschr:
5683 case Builtin::BI__builtin_wcschr:
5684 StopAtNull = true;
5685 // Fall through.
5686 case Builtin::BIwmemchr:
5687 case Builtin::BI__builtin_wmemchr:
5688 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5689 DesiredVal = Desired.getZExtValue();
5690 break;
5691 }
Richard Smithe9507952016-11-12 01:39:56 +00005692
5693 for (; MaxLength; --MaxLength) {
5694 APValue Char;
5695 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5696 !Char.isInt())
5697 return false;
5698 if (Char.getInt().getZExtValue() == DesiredVal)
5699 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005700 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005701 break;
5702 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5703 return false;
5704 }
5705 // Not found: return nullptr.
5706 return ZeroInitialization(E);
5707 }
5708
Richard Smith6cbd65d2013-07-11 02:27:57 +00005709 default:
George Burgess IVa7470272016-12-20 01:05:42 +00005710 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005711 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005712}
Chris Lattner05706e882008-07-11 18:11:29 +00005713
5714//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005715// Member Pointer Evaluation
5716//===----------------------------------------------------------------------===//
5717
5718namespace {
5719class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005720 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005721 MemberPtr &Result;
5722
5723 bool Success(const ValueDecl *D) {
5724 Result = MemberPtr(D);
5725 return true;
5726 }
5727public:
5728
5729 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5730 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5731
Richard Smith2e312c82012-03-03 22:46:17 +00005732 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005733 Result.setFrom(V);
5734 return true;
5735 }
Richard Smithfddd3842011-12-30 21:15:51 +00005736 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005737 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005738 }
5739
5740 bool VisitCastExpr(const CastExpr *E);
5741 bool VisitUnaryAddrOf(const UnaryOperator *E);
5742};
5743} // end anonymous namespace
5744
5745static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5746 EvalInfo &Info) {
5747 assert(E->isRValue() && E->getType()->isMemberPointerType());
5748 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5749}
5750
5751bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5752 switch (E->getCastKind()) {
5753 default:
5754 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5755
5756 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005757 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005758 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005759
5760 case CK_BaseToDerivedMemberPointer: {
5761 if (!Visit(E->getSubExpr()))
5762 return false;
5763 if (E->path_empty())
5764 return true;
5765 // Base-to-derived member pointer casts store the path in derived-to-base
5766 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5767 // the wrong end of the derived->base arc, so stagger the path by one class.
5768 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5769 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5770 PathI != PathE; ++PathI) {
5771 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5772 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5773 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005774 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005775 }
5776 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5777 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005778 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005779 return true;
5780 }
5781
5782 case CK_DerivedToBaseMemberPointer:
5783 if (!Visit(E->getSubExpr()))
5784 return false;
5785 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5786 PathE = E->path_end(); PathI != PathE; ++PathI) {
5787 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5788 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5789 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005790 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005791 }
5792 return true;
5793 }
5794}
5795
5796bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5797 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5798 // member can be formed.
5799 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5800}
5801
5802//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005803// Record Evaluation
5804//===----------------------------------------------------------------------===//
5805
5806namespace {
5807 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005808 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005809 const LValue &This;
5810 APValue &Result;
5811 public:
5812
5813 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5814 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5815
Richard Smith2e312c82012-03-03 22:46:17 +00005816 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005817 Result = V;
5818 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005819 }
Richard Smithb8348f52016-05-12 22:16:28 +00005820 bool ZeroInitialization(const Expr *E) {
5821 return ZeroInitialization(E, E->getType());
5822 }
5823 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005824
Richard Smith52a980a2015-08-28 02:43:42 +00005825 bool VisitCallExpr(const CallExpr *E) {
5826 return handleCallExpr(E, Result, &This);
5827 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005828 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005829 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005830 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5831 return VisitCXXConstructExpr(E, E->getType());
5832 }
Richard Smith5179eb72016-06-28 19:03:57 +00005833 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005834 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005835 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005836 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005837}
Richard Smithd62306a2011-11-10 06:34:14 +00005838
Richard Smithfddd3842011-12-30 21:15:51 +00005839/// Perform zero-initialization on an object of non-union class type.
5840/// C++11 [dcl.init]p5:
5841/// To zero-initialize an object or reference of type T means:
5842/// [...]
5843/// -- if T is a (possibly cv-qualified) non-union class type,
5844/// each non-static data member and each base-class subobject is
5845/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005846static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5847 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005848 const LValue &This, APValue &Result) {
5849 assert(!RD->isUnion() && "Expected non-union class type");
5850 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5851 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005852 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005853
John McCalld7bca762012-05-01 00:38:49 +00005854 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005855 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5856
5857 if (CD) {
5858 unsigned Index = 0;
5859 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005860 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005861 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5862 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005863 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5864 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005865 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005866 Result.getStructBase(Index)))
5867 return false;
5868 }
5869 }
5870
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005871 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005872 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005873 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005874 continue;
5875
5876 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005877 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005878 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005879
David Blaikie2d7c57e2012-04-30 02:36:29 +00005880 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005881 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005882 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005883 return false;
5884 }
5885
5886 return true;
5887}
5888
Richard Smithb8348f52016-05-12 22:16:28 +00005889bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5890 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005891 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005892 if (RD->isUnion()) {
5893 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5894 // object's first non-static named data member is zero-initialized
5895 RecordDecl::field_iterator I = RD->field_begin();
5896 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005897 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005898 return true;
5899 }
5900
5901 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005902 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005903 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005904 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005905 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005906 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005907 }
5908
Richard Smith5d108602012-02-17 00:44:16 +00005909 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005910 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005911 return false;
5912 }
5913
Richard Smitha8105bc2012-01-06 16:39:00 +00005914 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005915}
5916
Richard Smithe97cbd72011-11-11 04:05:33 +00005917bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5918 switch (E->getCastKind()) {
5919 default:
5920 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5921
5922 case CK_ConstructorConversion:
5923 return Visit(E->getSubExpr());
5924
5925 case CK_DerivedToBase:
5926 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005927 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005928 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005929 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005930 if (!DerivedObject.isStruct())
5931 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005932
5933 // Derived-to-base rvalue conversion: just slice off the derived part.
5934 APValue *Value = &DerivedObject;
5935 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5936 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5937 PathE = E->path_end(); PathI != PathE; ++PathI) {
5938 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5939 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5940 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5941 RD = Base;
5942 }
5943 Result = *Value;
5944 return true;
5945 }
5946 }
5947}
5948
Richard Smithd62306a2011-11-10 06:34:14 +00005949bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00005950 if (E->isTransparent())
5951 return Visit(E->getInit(0));
5952
Richard Smithd62306a2011-11-10 06:34:14 +00005953 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005954 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005955 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5956
5957 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005958 const FieldDecl *Field = E->getInitializedFieldInUnion();
5959 Result = APValue(Field);
5960 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005961 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005962
5963 // If the initializer list for a union does not contain any elements, the
5964 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005965 // FIXME: The element should be initialized from an initializer list.
5966 // Is this difference ever observable for initializer lists which
5967 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005968 ImplicitValueInitExpr VIE(Field->getType());
5969 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5970
Richard Smithd62306a2011-11-10 06:34:14 +00005971 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005972 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5973 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005974
5975 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5976 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5977 isa<CXXDefaultInitExpr>(InitExpr));
5978
Richard Smithb228a862012-02-15 02:18:13 +00005979 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005980 }
5981
Richard Smith872307e2016-03-08 22:17:41 +00005982 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00005983 if (Result.isUninit())
5984 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
5985 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005986 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005987 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00005988
5989 // Initialize base classes.
5990 if (CXXRD) {
5991 for (const auto &Base : CXXRD->bases()) {
5992 assert(ElementNo < E->getNumInits() && "missing init for base class");
5993 const Expr *Init = E->getInit(ElementNo);
5994
5995 LValue Subobject = This;
5996 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
5997 return false;
5998
5999 APValue &FieldVal = Result.getStructBase(ElementNo);
6000 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006001 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006002 return false;
6003 Success = false;
6004 }
6005 ++ElementNo;
6006 }
6007 }
6008
6009 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006010 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006011 // Anonymous bit-fields are not considered members of the class for
6012 // purposes of aggregate initialization.
6013 if (Field->isUnnamedBitfield())
6014 continue;
6015
6016 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006017
Richard Smith253c2a32012-01-27 01:14:48 +00006018 bool HaveInit = ElementNo < E->getNumInits();
6019
6020 // FIXME: Diagnostics here should point to the end of the initializer
6021 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006022 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006023 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006024 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006025
6026 // Perform an implicit value-initialization for members beyond the end of
6027 // the initializer list.
6028 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006029 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006030
Richard Smith852c9db2013-04-20 22:23:05 +00006031 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6032 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6033 isa<CXXDefaultInitExpr>(Init));
6034
Richard Smith49ca8aa2013-08-06 07:09:20 +00006035 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6036 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6037 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006038 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006039 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006040 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006041 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006042 }
6043 }
6044
Richard Smith253c2a32012-01-27 01:14:48 +00006045 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006046}
6047
Richard Smithb8348f52016-05-12 22:16:28 +00006048bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6049 QualType T) {
6050 // Note that E's type is not necessarily the type of our class here; we might
6051 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006052 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006053 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6054
Richard Smithfddd3842011-12-30 21:15:51 +00006055 bool ZeroInit = E->requiresZeroInitialization();
6056 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006057 // If we've already performed zero-initialization, we're already done.
6058 if (!Result.isUninit())
6059 return true;
6060
Richard Smithda3f4fd2014-03-05 23:32:50 +00006061 // We can get here in two different ways:
6062 // 1) We're performing value-initialization, and should zero-initialize
6063 // the object, or
6064 // 2) We're performing default-initialization of an object with a trivial
6065 // constexpr default constructor, in which case we should start the
6066 // lifetimes of all the base subobjects (there can be no data member
6067 // subobjects in this case) per [basic.life]p1.
6068 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006069 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006070 }
6071
Craig Topper36250ad2014-05-12 05:36:57 +00006072 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006073 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006074
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006075 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006076 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006077
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006078 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006079 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006080 if (const MaterializeTemporaryExpr *ME
6081 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6082 return Visit(ME->GetTemporaryExpr());
6083
Richard Smithb8348f52016-05-12 22:16:28 +00006084 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006085 return false;
6086
Craig Topper5fc8fc22014-08-27 06:28:36 +00006087 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006088 return HandleConstructorCall(E, This, Args,
6089 cast<CXXConstructorDecl>(Definition), Info,
6090 Result);
6091}
6092
6093bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6094 const CXXInheritedCtorInitExpr *E) {
6095 if (!Info.CurrentCall) {
6096 assert(Info.checkingPotentialConstantExpression());
6097 return false;
6098 }
6099
6100 const CXXConstructorDecl *FD = E->getConstructor();
6101 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6102 return false;
6103
6104 const FunctionDecl *Definition = nullptr;
6105 auto Body = FD->getBody(Definition);
6106
6107 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6108 return false;
6109
6110 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006111 cast<CXXConstructorDecl>(Definition), Info,
6112 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006113}
6114
Richard Smithcc1b96d2013-06-12 22:31:48 +00006115bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6116 const CXXStdInitializerListExpr *E) {
6117 const ConstantArrayType *ArrayType =
6118 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6119
6120 LValue Array;
6121 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6122 return false;
6123
6124 // Get a pointer to the first element of the array.
6125 Array.addArray(Info, E, ArrayType);
6126
6127 // FIXME: Perform the checks on the field types in SemaInit.
6128 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6129 RecordDecl::field_iterator Field = Record->field_begin();
6130 if (Field == Record->field_end())
6131 return Error(E);
6132
6133 // Start pointer.
6134 if (!Field->getType()->isPointerType() ||
6135 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6136 ArrayType->getElementType()))
6137 return Error(E);
6138
6139 // FIXME: What if the initializer_list type has base classes, etc?
6140 Result = APValue(APValue::UninitStruct(), 0, 2);
6141 Array.moveInto(Result.getStructField(0));
6142
6143 if (++Field == Record->field_end())
6144 return Error(E);
6145
6146 if (Field->getType()->isPointerType() &&
6147 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6148 ArrayType->getElementType())) {
6149 // End pointer.
6150 if (!HandleLValueArrayAdjustment(Info, E, Array,
6151 ArrayType->getElementType(),
6152 ArrayType->getSize().getZExtValue()))
6153 return false;
6154 Array.moveInto(Result.getStructField(1));
6155 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6156 // Length.
6157 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6158 else
6159 return Error(E);
6160
6161 if (++Field != Record->field_end())
6162 return Error(E);
6163
6164 return true;
6165}
6166
Richard Smithd62306a2011-11-10 06:34:14 +00006167static bool EvaluateRecord(const Expr *E, const LValue &This,
6168 APValue &Result, EvalInfo &Info) {
6169 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006170 "can't evaluate expression as a record rvalue");
6171 return RecordExprEvaluator(Info, This, Result).Visit(E);
6172}
6173
6174//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006175// Temporary Evaluation
6176//
6177// Temporaries are represented in the AST as rvalues, but generally behave like
6178// lvalues. The full-object of which the temporary is a subobject is implicitly
6179// materialized so that a reference can bind to it.
6180//===----------------------------------------------------------------------===//
6181namespace {
6182class TemporaryExprEvaluator
6183 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6184public:
6185 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6186 LValueExprEvaluatorBaseTy(Info, Result) {}
6187
6188 /// Visit an expression which constructs the value of this temporary.
6189 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006190 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006191 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6192 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006193 }
6194
6195 bool VisitCastExpr(const CastExpr *E) {
6196 switch (E->getCastKind()) {
6197 default:
6198 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6199
6200 case CK_ConstructorConversion:
6201 return VisitConstructExpr(E->getSubExpr());
6202 }
6203 }
6204 bool VisitInitListExpr(const InitListExpr *E) {
6205 return VisitConstructExpr(E);
6206 }
6207 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6208 return VisitConstructExpr(E);
6209 }
6210 bool VisitCallExpr(const CallExpr *E) {
6211 return VisitConstructExpr(E);
6212 }
Richard Smith513955c2014-12-17 19:24:30 +00006213 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6214 return VisitConstructExpr(E);
6215 }
Richard Smith027bf112011-11-17 22:56:20 +00006216};
6217} // end anonymous namespace
6218
6219/// Evaluate an expression of record type as a temporary.
6220static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006221 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006222 return TemporaryExprEvaluator(Info, Result).Visit(E);
6223}
6224
6225//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006226// Vector Evaluation
6227//===----------------------------------------------------------------------===//
6228
6229namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006230 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006231 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006232 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006233 public:
Mike Stump11289f42009-09-09 15:08:12 +00006234
Richard Smith2d406342011-10-22 21:10:00 +00006235 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6236 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006237
Craig Topper9798b932015-09-29 04:30:05 +00006238 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006239 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6240 // FIXME: remove this APValue copy.
6241 Result = APValue(V.data(), V.size());
6242 return true;
6243 }
Richard Smith2e312c82012-03-03 22:46:17 +00006244 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006245 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006246 Result = V;
6247 return true;
6248 }
Richard Smithfddd3842011-12-30 21:15:51 +00006249 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006250
Richard Smith2d406342011-10-22 21:10:00 +00006251 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006252 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006253 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006254 bool VisitInitListExpr(const InitListExpr *E);
6255 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006256 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006257 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006258 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006259 };
6260} // end anonymous namespace
6261
6262static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006263 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006264 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006265}
6266
George Burgess IV533ff002015-12-11 00:23:35 +00006267bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006268 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006269 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006270
Richard Smith161f09a2011-12-06 22:44:34 +00006271 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006272 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006273
Eli Friedmanc757de22011-03-25 00:43:55 +00006274 switch (E->getCastKind()) {
6275 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006276 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006277 if (SETy->isIntegerType()) {
6278 APSInt IntResult;
6279 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006280 return false;
6281 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006282 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006283 APFloat FloatResult(0.0);
6284 if (!EvaluateFloat(SE, FloatResult, Info))
6285 return false;
6286 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006287 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006288 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006289 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006290
6291 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006292 SmallVector<APValue, 4> Elts(NElts, Val);
6293 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006294 }
Eli Friedman803acb32011-12-22 03:51:45 +00006295 case CK_BitCast: {
6296 // Evaluate the operand into an APInt we can extract from.
6297 llvm::APInt SValInt;
6298 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6299 return false;
6300 // Extract the elements
6301 QualType EltTy = VTy->getElementType();
6302 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6303 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6304 SmallVector<APValue, 4> Elts;
6305 if (EltTy->isRealFloatingType()) {
6306 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006307 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006308 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006309 FloatEltSize = 80;
6310 for (unsigned i = 0; i < NElts; i++) {
6311 llvm::APInt Elt;
6312 if (BigEndian)
6313 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6314 else
6315 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006316 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006317 }
6318 } else if (EltTy->isIntegerType()) {
6319 for (unsigned i = 0; i < NElts; i++) {
6320 llvm::APInt Elt;
6321 if (BigEndian)
6322 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6323 else
6324 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6325 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6326 }
6327 } else {
6328 return Error(E);
6329 }
6330 return Success(Elts, E);
6331 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006332 default:
Richard Smith11562c52011-10-28 17:51:58 +00006333 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006334 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006335}
6336
Richard Smith2d406342011-10-22 21:10:00 +00006337bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006338VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006339 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006340 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006341 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006342
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006343 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006344 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006345
Eli Friedmanb9c71292012-01-03 23:24:20 +00006346 // The number of initializers can be less than the number of
6347 // vector elements. For OpenCL, this can be due to nested vector
6348 // initialization. For GCC compatibility, missing trailing elements
6349 // should be initialized with zeroes.
6350 unsigned CountInits = 0, CountElts = 0;
6351 while (CountElts < NumElements) {
6352 // Handle nested vector initialization.
6353 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006354 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006355 APValue v;
6356 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6357 return Error(E);
6358 unsigned vlen = v.getVectorLength();
6359 for (unsigned j = 0; j < vlen; j++)
6360 Elements.push_back(v.getVectorElt(j));
6361 CountElts += vlen;
6362 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006363 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006364 if (CountInits < NumInits) {
6365 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006366 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006367 } else // trailing integer zero.
6368 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6369 Elements.push_back(APValue(sInt));
6370 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006371 } else {
6372 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006373 if (CountInits < NumInits) {
6374 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006375 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006376 } else // trailing float zero.
6377 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6378 Elements.push_back(APValue(f));
6379 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006380 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006381 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006382 }
Richard Smith2d406342011-10-22 21:10:00 +00006383 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006384}
6385
Richard Smith2d406342011-10-22 21:10:00 +00006386bool
Richard Smithfddd3842011-12-30 21:15:51 +00006387VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006388 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006389 QualType EltTy = VT->getElementType();
6390 APValue ZeroElement;
6391 if (EltTy->isIntegerType())
6392 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6393 else
6394 ZeroElement =
6395 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6396
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006397 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006398 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006399}
6400
Richard Smith2d406342011-10-22 21:10:00 +00006401bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006402 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006403 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006404}
6405
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006406//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006407// Array Evaluation
6408//===----------------------------------------------------------------------===//
6409
6410namespace {
6411 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006412 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006413 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006414 APValue &Result;
6415 public:
6416
Richard Smithd62306a2011-11-10 06:34:14 +00006417 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6418 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006419
6420 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006421 assert((V.isArray() || V.isLValue()) &&
6422 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006423 Result = V;
6424 return true;
6425 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006426
Richard Smithfddd3842011-12-30 21:15:51 +00006427 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006428 const ConstantArrayType *CAT =
6429 Info.Ctx.getAsConstantArrayType(E->getType());
6430 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006431 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006432
6433 Result = APValue(APValue::UninitArray(), 0,
6434 CAT->getSize().getZExtValue());
6435 if (!Result.hasArrayFiller()) return true;
6436
Richard Smithfddd3842011-12-30 21:15:51 +00006437 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006438 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006439 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006440 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006441 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006442 }
6443
Richard Smith52a980a2015-08-28 02:43:42 +00006444 bool VisitCallExpr(const CallExpr *E) {
6445 return handleCallExpr(E, Result, &This);
6446 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006447 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006448 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006449 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006450 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6451 const LValue &Subobject,
6452 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006453 };
6454} // end anonymous namespace
6455
Richard Smithd62306a2011-11-10 06:34:14 +00006456static bool EvaluateArray(const Expr *E, const LValue &This,
6457 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006458 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006459 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006460}
6461
6462bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6463 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6464 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006465 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006466
Richard Smithca2cfbf2011-12-22 01:07:19 +00006467 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6468 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006469 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006470 LValue LV;
6471 if (!EvaluateLValue(E->getInit(0), LV, Info))
6472 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006473 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006474 LV.moveInto(Val);
6475 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006476 }
6477
Richard Smith253c2a32012-01-27 01:14:48 +00006478 bool Success = true;
6479
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006480 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6481 "zero-initialized array shouldn't have any initialized elts");
6482 APValue Filler;
6483 if (Result.isArray() && Result.hasArrayFiller())
6484 Filler = Result.getArrayFiller();
6485
Richard Smith9543c5e2013-04-22 14:44:29 +00006486 unsigned NumEltsToInit = E->getNumInits();
6487 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006488 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006489
6490 // If the initializer might depend on the array index, run it for each
6491 // array element. For now, just whitelist non-class value-initialization.
6492 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6493 NumEltsToInit = NumElts;
6494
6495 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006496
6497 // If the array was previously zero-initialized, preserve the
6498 // zero-initialized values.
6499 if (!Filler.isUninit()) {
6500 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6501 Result.getArrayInitializedElt(I) = Filler;
6502 if (Result.hasArrayFiller())
6503 Result.getArrayFiller() = Filler;
6504 }
6505
Richard Smithd62306a2011-11-10 06:34:14 +00006506 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006507 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006508 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6509 const Expr *Init =
6510 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006511 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006512 Info, Subobject, Init) ||
6513 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006514 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006515 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006516 return false;
6517 Success = false;
6518 }
Richard Smithd62306a2011-11-10 06:34:14 +00006519 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006520
Richard Smith9543c5e2013-04-22 14:44:29 +00006521 if (!Result.hasArrayFiller())
6522 return Success;
6523
6524 // If we get here, we have a trivial filler, which we can just evaluate
6525 // once and splat over the rest of the array elements.
6526 assert(FillerExpr && "no array filler for incomplete init list");
6527 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6528 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006529}
6530
Richard Smith410306b2016-12-12 02:53:20 +00006531bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6532 if (E->getCommonExpr() &&
6533 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6534 Info, E->getCommonExpr()->getSourceExpr()))
6535 return false;
6536
6537 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6538
6539 uint64_t Elements = CAT->getSize().getZExtValue();
6540 Result = APValue(APValue::UninitArray(), Elements, Elements);
6541
6542 LValue Subobject = This;
6543 Subobject.addArray(Info, E, CAT);
6544
6545 bool Success = true;
6546 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6547 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6548 Info, Subobject, E->getSubExpr()) ||
6549 !HandleLValueArrayAdjustment(Info, E, Subobject,
6550 CAT->getElementType(), 1)) {
6551 if (!Info.noteFailure())
6552 return false;
6553 Success = false;
6554 }
6555 }
6556
6557 return Success;
6558}
6559
Richard Smith027bf112011-11-17 22:56:20 +00006560bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006561 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6562}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006563
Richard Smith9543c5e2013-04-22 14:44:29 +00006564bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6565 const LValue &Subobject,
6566 APValue *Value,
6567 QualType Type) {
6568 bool HadZeroInit = !Value->isUninit();
6569
6570 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6571 unsigned N = CAT->getSize().getZExtValue();
6572
6573 // Preserve the array filler if we had prior zero-initialization.
6574 APValue Filler =
6575 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6576 : APValue();
6577
6578 *Value = APValue(APValue::UninitArray(), N, N);
6579
6580 if (HadZeroInit)
6581 for (unsigned I = 0; I != N; ++I)
6582 Value->getArrayInitializedElt(I) = Filler;
6583
6584 // Initialize the elements.
6585 LValue ArrayElt = Subobject;
6586 ArrayElt.addArray(Info, E, CAT);
6587 for (unsigned I = 0; I != N; ++I)
6588 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6589 CAT->getElementType()) ||
6590 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6591 CAT->getElementType(), 1))
6592 return false;
6593
6594 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006595 }
Richard Smith027bf112011-11-17 22:56:20 +00006596
Richard Smith9543c5e2013-04-22 14:44:29 +00006597 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006598 return Error(E);
6599
Richard Smithb8348f52016-05-12 22:16:28 +00006600 return RecordExprEvaluator(Info, Subobject, *Value)
6601 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006602}
6603
Richard Smithf3e9e432011-11-07 09:22:26 +00006604//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006605// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006606//
6607// As a GNU extension, we support casting pointers to sufficiently-wide integer
6608// types and back in constant folding. Integer values are thus represented
6609// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006610//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006611
6612namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006613class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006614 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006615 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006616public:
Richard Smith2e312c82012-03-03 22:46:17 +00006617 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006618 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006619
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006620 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006621 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006622 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006623 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006624 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006625 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006626 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006627 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006628 return true;
6629 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006630 bool Success(const llvm::APSInt &SI, const Expr *E) {
6631 return Success(SI, E, Result);
6632 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006633
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006634 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006635 assert(E->getType()->isIntegralOrEnumerationType() &&
6636 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006637 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006638 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006639 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006640 Result.getInt().setIsUnsigned(
6641 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006642 return true;
6643 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006644 bool Success(const llvm::APInt &I, const Expr *E) {
6645 return Success(I, E, Result);
6646 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006647
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006648 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006649 assert(E->getType()->isIntegralOrEnumerationType() &&
6650 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006651 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006652 return true;
6653 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006654 bool Success(uint64_t Value, const Expr *E) {
6655 return Success(Value, E, Result);
6656 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006657
Ken Dyckdbc01912011-03-11 02:13:43 +00006658 bool Success(CharUnits Size, const Expr *E) {
6659 return Success(Size.getQuantity(), E);
6660 }
6661
Richard Smith2e312c82012-03-03 22:46:17 +00006662 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006663 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006664 Result = V;
6665 return true;
6666 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006667 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006668 }
Mike Stump11289f42009-09-09 15:08:12 +00006669
Richard Smithfddd3842011-12-30 21:15:51 +00006670 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006671
Peter Collingbournee9200682011-05-13 03:29:01 +00006672 //===--------------------------------------------------------------------===//
6673 // Visitor Methods
6674 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006675
Chris Lattner7174bf32008-07-12 00:38:25 +00006676 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006677 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006678 }
6679 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006680 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006681 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006682
6683 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6684 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006685 if (CheckReferencedDecl(E, E->getDecl()))
6686 return true;
6687
6688 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006689 }
6690 bool VisitMemberExpr(const MemberExpr *E) {
6691 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006692 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006693 return true;
6694 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006695
6696 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006697 }
6698
Peter Collingbournee9200682011-05-13 03:29:01 +00006699 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006700 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006701 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006702 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006703 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006704
Peter Collingbournee9200682011-05-13 03:29:01 +00006705 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006706 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006707
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006708 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006709 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006710 }
Mike Stump11289f42009-09-09 15:08:12 +00006711
Ted Kremeneke65b0862012-03-06 20:05:56 +00006712 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6713 return Success(E->getValue(), E);
6714 }
Richard Smith410306b2016-12-12 02:53:20 +00006715
6716 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6717 if (Info.ArrayInitIndex == uint64_t(-1)) {
6718 // We were asked to evaluate this subexpression independent of the
6719 // enclosing ArrayInitLoopExpr. We can't do that.
6720 Info.FFDiag(E);
6721 return false;
6722 }
6723 return Success(Info.ArrayInitIndex, E);
6724 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00006725
Richard Smith4ce706a2011-10-11 21:43:33 +00006726 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006727 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006728 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006729 }
6730
Douglas Gregor29c42f22012-02-24 07:38:34 +00006731 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6732 return Success(E->getValue(), E);
6733 }
6734
John Wiegley6242b6a2011-04-28 00:16:57 +00006735 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6736 return Success(E->getValue(), E);
6737 }
6738
John Wiegleyf9f65842011-04-25 06:54:41 +00006739 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6740 return Success(E->getValue(), E);
6741 }
6742
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006743 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006744 bool VisitUnaryImag(const UnaryOperator *E);
6745
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006746 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006747 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006748
Eli Friedman4e7a2412009-02-27 04:45:43 +00006749 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006750};
Chris Lattner05706e882008-07-11 18:11:29 +00006751} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006752
Richard Smith11562c52011-10-28 17:51:58 +00006753/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6754/// produce either the integer value or a pointer.
6755///
6756/// GCC has a heinous extension which folds casts between pointer types and
6757/// pointer-sized integral types. We support this by allowing the evaluation of
6758/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6759/// Some simple arithmetic on such values is supported (they are treated much
6760/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006761static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006762 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006763 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006764 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006765}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006766
Richard Smithf57d8cb2011-12-09 22:58:01 +00006767static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006768 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006769 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006770 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006771 if (!Val.isInt()) {
6772 // FIXME: It would be better to produce the diagnostic for casting
6773 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00006774 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006775 return false;
6776 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006777 Result = Val.getInt();
6778 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006779}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006780
Richard Smithf57d8cb2011-12-09 22:58:01 +00006781/// Check whether the given declaration can be directly converted to an integral
6782/// rvalue. If not, no diagnostic is produced; there are other things we can
6783/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006784bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006785 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006786 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006787 // Check for signedness/width mismatches between E type and ECD value.
6788 bool SameSign = (ECD->getInitVal().isSigned()
6789 == E->getType()->isSignedIntegerOrEnumerationType());
6790 bool SameWidth = (ECD->getInitVal().getBitWidth()
6791 == Info.Ctx.getIntWidth(E->getType()));
6792 if (SameSign && SameWidth)
6793 return Success(ECD->getInitVal(), E);
6794 else {
6795 // Get rid of mismatch (otherwise Success assertions will fail)
6796 // by computing a new value matching the type of E.
6797 llvm::APSInt Val = ECD->getInitVal();
6798 if (!SameSign)
6799 Val.setIsSigned(!ECD->getInitVal().isSigned());
6800 if (!SameWidth)
6801 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6802 return Success(Val, E);
6803 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006804 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006805 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006806}
6807
Chris Lattner86ee2862008-10-06 06:40:35 +00006808/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6809/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006810static int EvaluateBuiltinClassifyType(const CallExpr *E,
6811 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006812 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006813 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006814 enum gcc_type_class {
6815 no_type_class = -1,
6816 void_type_class, integer_type_class, char_type_class,
6817 enumeral_type_class, boolean_type_class,
6818 pointer_type_class, reference_type_class, offset_type_class,
6819 real_type_class, complex_type_class,
6820 function_type_class, method_type_class,
6821 record_type_class, union_type_class,
6822 array_type_class, string_type_class,
6823 lang_type_class
6824 };
Mike Stump11289f42009-09-09 15:08:12 +00006825
6826 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006827 // ideal, however it is what gcc does.
6828 if (E->getNumArgs() == 0)
6829 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006830
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006831 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6832 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6833
6834 switch (CanTy->getTypeClass()) {
6835#define TYPE(ID, BASE)
6836#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6837#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6838#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6839#include "clang/AST/TypeNodes.def"
6840 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6841
6842 case Type::Builtin:
6843 switch (BT->getKind()) {
6844#define BUILTIN_TYPE(ID, SINGLETON_ID)
6845#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6846#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6847#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6848#include "clang/AST/BuiltinTypes.def"
6849 case BuiltinType::Void:
6850 return void_type_class;
6851
6852 case BuiltinType::Bool:
6853 return boolean_type_class;
6854
6855 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6856 case BuiltinType::UChar:
6857 case BuiltinType::UShort:
6858 case BuiltinType::UInt:
6859 case BuiltinType::ULong:
6860 case BuiltinType::ULongLong:
6861 case BuiltinType::UInt128:
6862 return integer_type_class;
6863
6864 case BuiltinType::NullPtr:
6865 return pointer_type_class;
6866
6867 case BuiltinType::WChar_U:
6868 case BuiltinType::Char16:
6869 case BuiltinType::Char32:
6870 case BuiltinType::ObjCId:
6871 case BuiltinType::ObjCClass:
6872 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00006873#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6874 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006875#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006876 case BuiltinType::OCLSampler:
6877 case BuiltinType::OCLEvent:
6878 case BuiltinType::OCLClkEvent:
6879 case BuiltinType::OCLQueue:
6880 case BuiltinType::OCLNDRange:
6881 case BuiltinType::OCLReserveID:
6882 case BuiltinType::Dependent:
6883 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6884 };
6885
6886 case Type::Enum:
6887 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6888 break;
6889
6890 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00006891 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006892 break;
6893
6894 case Type::MemberPointer:
6895 if (CanTy->isMemberDataPointerType())
6896 return offset_type_class;
6897 else {
6898 // We expect member pointers to be either data or function pointers,
6899 // nothing else.
6900 assert(CanTy->isMemberFunctionPointerType());
6901 return method_type_class;
6902 }
6903
6904 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00006905 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006906
6907 case Type::FunctionNoProto:
6908 case Type::FunctionProto:
6909 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6910
6911 case Type::Record:
6912 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6913 switch (RT->getDecl()->getTagKind()) {
6914 case TagTypeKind::TTK_Struct:
6915 case TagTypeKind::TTK_Class:
6916 case TagTypeKind::TTK_Interface:
6917 return record_type_class;
6918
6919 case TagTypeKind::TTK_Enum:
6920 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6921
6922 case TagTypeKind::TTK_Union:
6923 return union_type_class;
6924 }
6925 }
David Blaikie83d382b2011-09-23 05:06:16 +00006926 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006927
6928 case Type::ConstantArray:
6929 case Type::VariableArray:
6930 case Type::IncompleteArray:
6931 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
6932
6933 case Type::BlockPointer:
6934 case Type::LValueReference:
6935 case Type::RValueReference:
6936 case Type::Vector:
6937 case Type::ExtVector:
6938 case Type::Auto:
6939 case Type::ObjCObject:
6940 case Type::ObjCInterface:
6941 case Type::ObjCObjectPointer:
6942 case Type::Pipe:
6943 case Type::Atomic:
6944 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6945 }
6946
6947 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006948}
6949
Richard Smith5fab0c92011-12-28 19:48:30 +00006950/// EvaluateBuiltinConstantPForLValue - Determine the result of
6951/// __builtin_constant_p when applied to the given lvalue.
6952///
6953/// An lvalue is only "constant" if it is a pointer or reference to the first
6954/// character of a string literal.
6955template<typename LValue>
6956static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006957 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006958 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6959}
6960
6961/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6962/// GCC as we can manage.
6963static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6964 QualType ArgType = Arg->getType();
6965
6966 // __builtin_constant_p always has one operand. The rules which gcc follows
6967 // are not precisely documented, but are as follows:
6968 //
6969 // - If the operand is of integral, floating, complex or enumeration type,
6970 // and can be folded to a known value of that type, it returns 1.
6971 // - If the operand and can be folded to a pointer to the first character
6972 // of a string literal (or such a pointer cast to an integral type), it
6973 // returns 1.
6974 //
6975 // Otherwise, it returns 0.
6976 //
6977 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6978 // its support for this does not currently work.
6979 if (ArgType->isIntegralOrEnumerationType()) {
6980 Expr::EvalResult Result;
6981 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6982 return false;
6983
6984 APValue &V = Result.Val;
6985 if (V.getKind() == APValue::Int)
6986 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00006987 if (V.getKind() == APValue::LValue)
6988 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00006989 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6990 return Arg->isEvaluatable(Ctx);
6991 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6992 LValue LV;
6993 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006994 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006995 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6996 : EvaluatePointer(Arg, LV, Info)) &&
6997 !Status.HasSideEffects)
6998 return EvaluateBuiltinConstantPForLValue(LV);
6999 }
7000
7001 // Anything else isn't considered to be sufficiently constant.
7002 return false;
7003}
7004
John McCall95007602010-05-10 23:27:23 +00007005/// Retrieves the "underlying object type" of the given expression,
7006/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007007static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007008 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7009 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007010 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007011 } else if (const Expr *E = B.get<const Expr*>()) {
7012 if (isa<CompoundLiteralExpr>(E))
7013 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007014 }
7015
7016 return QualType();
7017}
7018
George Burgess IV3a03fab2015-09-04 21:28:13 +00007019/// A more selective version of E->IgnoreParenCasts for
George Burgess IVa7470272016-12-20 01:05:42 +00007020/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007021/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007022/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7023///
7024/// Always returns an RValue with a pointer representation.
7025static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7026 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7027
7028 auto *NoParens = E->IgnoreParens();
7029 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007030 if (Cast == nullptr)
7031 return NoParens;
7032
7033 // We only conservatively allow a few kinds of casts, because this code is
7034 // inherently a simple solution that seeks to support the common case.
7035 auto CastKind = Cast->getCastKind();
7036 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7037 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007038 return NoParens;
7039
7040 auto *SubExpr = Cast->getSubExpr();
7041 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7042 return NoParens;
7043 return ignorePointerCastsAndParens(SubExpr);
7044}
7045
George Burgess IVa51c4072015-10-16 01:49:01 +00007046/// Checks to see if the given LValue's Designator is at the end of the LValue's
7047/// record layout. e.g.
7048/// struct { struct { int a, b; } fst, snd; } obj;
7049/// obj.fst // no
7050/// obj.snd // yes
7051/// obj.fst.a // no
7052/// obj.fst.b // no
7053/// obj.snd.a // no
7054/// obj.snd.b // yes
7055///
7056/// Please note: this function is specialized for how __builtin_object_size
7057/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007058///
7059/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007060static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7061 assert(!LVal.Designator.Invalid);
7062
George Burgess IV4168d752016-06-27 19:40:41 +00007063 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7064 const RecordDecl *Parent = FD->getParent();
7065 Invalid = Parent->isInvalidDecl();
7066 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007067 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007068 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007069 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7070 };
7071
7072 auto &Base = LVal.getLValueBase();
7073 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7074 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007075 bool Invalid;
7076 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7077 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007078 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007079 for (auto *FD : IFD->chain()) {
7080 bool Invalid;
7081 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7082 return Invalid;
7083 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007084 }
7085 }
7086
George Burgess IVa7470272016-12-20 01:05:42 +00007087 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007088 QualType BaseType = getType(Base);
George Burgess IVa7470272016-12-20 01:05:42 +00007089 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7090 assert(isBaseAnAllocSizeCall(Base) &&
7091 "Unsized array in non-alloc_size call?");
7092 // If this is an alloc_size base, we should ignore the initial array index
7093 ++I;
7094 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7095 }
7096
7097 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7098 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007099 if (BaseType->isArrayType()) {
7100 // Because __builtin_object_size treats arrays as objects, we can ignore
7101 // the index iff this is the last array in the Designator.
7102 if (I + 1 == E)
7103 return true;
George Burgess IVa7470272016-12-20 01:05:42 +00007104 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7105 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007106 if (Index + 1 != CAT->getSize())
7107 return false;
7108 BaseType = CAT->getElementType();
7109 } else if (BaseType->isAnyComplexType()) {
George Burgess IVa7470272016-12-20 01:05:42 +00007110 const auto *CT = BaseType->castAs<ComplexType>();
7111 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007112 if (Index != 1)
7113 return false;
7114 BaseType = CT->getElementType();
George Burgess IVa7470272016-12-20 01:05:42 +00007115 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007116 bool Invalid;
7117 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7118 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007119 BaseType = FD->getType();
7120 } else {
George Burgess IVa7470272016-12-20 01:05:42 +00007121 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007122 return false;
7123 }
7124 }
7125 return true;
7126}
7127
George Burgess IVa7470272016-12-20 01:05:42 +00007128/// Tests to see if the LValue has a user-specified designator (that isn't
7129/// necessarily valid). Note that this always returns 'true' if the LValue has
7130/// an unsized array as its first designator entry, because there's currently no
7131/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007132static bool refersToCompleteObject(const LValue &LVal) {
7133 if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
7134 return false;
7135
7136 if (!LVal.InvalidBase)
7137 return true;
7138
George Burgess IVa7470272016-12-20 01:05:42 +00007139 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7140 // the LValueBase.
7141 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7142 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007143}
7144
George Burgess IVa7470272016-12-20 01:05:42 +00007145/// Attempts to detect a user writing into a piece of memory that's impossible
7146/// to figure out the size of by just using types.
7147static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7148 const SubobjectDesignator &Designator = LVal.Designator;
7149 // Notes:
7150 // - Users can only write off of the end when we have an invalid base. Invalid
7151 // bases imply we don't know where the memory came from.
7152 // - We used to be a bit more aggressive here; we'd only be conservative if
7153 // the array at the end was flexible, or if it had 0 or 1 elements. This
7154 // broke some common standard library extensions (PR30346), but was
7155 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7156 // with some sort of whitelist. OTOH, it seems that GCC is always
7157 // conservative with the last element in structs (if it's an array), so our
7158 // current behavior is more compatible than a whitelisting approach would
7159 // be.
7160 return LVal.InvalidBase &&
7161 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7162 Designator.MostDerivedIsArrayElement &&
7163 isDesignatorAtObjectEnd(Ctx, LVal);
7164}
7165
7166/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7167/// Fails if the conversion would cause loss of precision.
7168static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7169 CharUnits &Result) {
7170 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7171 if (Int.ugt(CharUnitsMax))
7172 return false;
7173 Result = CharUnits::fromQuantity(Int.getZExtValue());
7174 return true;
7175}
7176
7177/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7178/// determine how many bytes exist from the beginning of the object to either
7179/// the end of the current subobject, or the end of the object itself, depending
7180/// on what the LValue looks like + the value of Type.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007181///
George Burgess IVa7470272016-12-20 01:05:42 +00007182/// If this returns false, the value of Result is undefined.
7183static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7184 unsigned Type, const LValue &LVal,
7185 CharUnits &EndOffset) {
7186 // __builtin_object_size(&foo, N) == __builtin_object_size(&foo, (N & ~1U)).
7187 // (Where foo is an expression that has no designator). Hence, if we've no
7188 // designator, we can ignore the subobject bit.
7189 bool EvaluateAsCompleteObject =
7190 !(Type & 1) || LVal.Designator.isMostDerivedAnUnsizedArray() ||
7191 refersToCompleteObject(LVal);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007192
George Burgess IVa7470272016-12-20 01:05:42 +00007193 // We want to evaluate the size of the entire object. This is a valid fallback
7194 // for when Type=1 and the designator is invalid, because we're asked for an
7195 // upper-bound.
7196 if (LVal.Designator.Invalid || EvaluateAsCompleteObject) {
7197 // We can't give a correct lower bound for Type=3 if the designator is
7198 // invalid and we're meant to be evaluating it.
7199 if (Type == 3 && LVal.Designator.Invalid && !EvaluateAsCompleteObject)
Richard Smith01ade172012-05-23 04:13:20 +00007200 return false;
George Burgess IVa7470272016-12-20 01:05:42 +00007201
7202 llvm::APInt APEndOffset;
7203 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7204 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7205 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7206
7207 if (LVal.InvalidBase)
7208 return false;
7209
7210 QualType BaseTy = getObjectType(LVal.getLValueBase());
7211 return !BaseTy.isNull() && HandleSizeof(Info, ExprLoc, BaseTy, EndOffset);
Richard Smith01ade172012-05-23 04:13:20 +00007212 }
John McCall95007602010-05-10 23:27:23 +00007213
George Burgess IVa7470272016-12-20 01:05:42 +00007214 // We want to evaluate the size of a subobject.
7215 const SubobjectDesignator &Designator = LVal.Designator;
George Burgess IVa51c4072015-10-16 01:49:01 +00007216
7217 // The following is a moderately common idiom in C:
7218 //
7219 // struct Foo { int a; char c[1]; };
7220 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7221 // strcpy(&F->c[0], Bar);
7222 //
George Burgess IVa7470272016-12-20 01:05:42 +00007223 // In order to not break too much legacy code, we need to support it.
7224 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7225 // If we can resolve this to an alloc_size call, we can hand that back,
7226 // because we know for certain how many bytes there are to write to.
7227 llvm::APInt APEndOffset;
7228 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7229 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7230 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7231
7232 // If we cannot determine the size of the initial allocation, then we can't
7233 // given an accurate upper-bound. However, we are still able to give
7234 // conservative lower-bounds for Type=3.
7235 if (Type == 1)
7236 return false;
7237 }
7238
7239 CharUnits BytesPerElem;
7240 if (!HandleSizeof(Info, ExprLoc, Designator.MostDerivedType, BytesPerElem))
George Burgess IVa51c4072015-10-16 01:49:01 +00007241 return false;
7242
George Burgess IVa7470272016-12-20 01:05:42 +00007243 // According to the GCC documentation, we want the size of the subobject
7244 // denoted by the pointer. But that's not quite right -- what we actually
7245 // want is the size of the immediately-enclosing array, if there is one.
7246 int64_t ElemsRemaining;
7247 if (Designator.MostDerivedIsArrayElement &&
7248 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7249 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7250 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7251 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7252 } else {
7253 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7254 }
George Burgess IVbdb5b262015-08-19 02:19:07 +00007255
George Burgess IVa7470272016-12-20 01:05:42 +00007256 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7257 return true;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007258}
7259
George Burgess IVa7470272016-12-20 01:05:42 +00007260/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7261/// returns true and stores the result in @p Size.
7262///
7263/// If @p WasError is non-null, this will report whether the failure to evaluate
7264/// is to be treated as an Error in IntExprEvaluator.
7265static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7266 EvalInfo &Info, uint64_t &Size) {
7267 // Determine the denoted object.
7268 LValue LVal;
7269 {
7270 // The operand of __builtin_object_size is never evaluated for side-effects.
7271 // If there are any, but we can determine the pointed-to object anyway, then
7272 // ignore the side-effects.
7273 SpeculativeEvaluationRAII SpeculativeEval(Info);
7274 FoldOffsetRAII Fold(Info);
7275
7276 if (E->isGLValue()) {
7277 // It's possible for us to be given GLValues if we're called via
7278 // Expr::tryEvaluateObjectSize.
7279 APValue RVal;
7280 if (!EvaluateAsRValue(Info, E, RVal))
7281 return false;
7282 LVal.setFrom(Info.Ctx, RVal);
7283 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info))
7284 return false;
7285 }
7286
7287 // If we point to before the start of the object, there are no accessible
7288 // bytes.
7289 if (LVal.getLValueOffset().isNegative()) {
7290 Size = 0;
7291 return true;
7292 }
7293
7294 CharUnits EndOffset;
7295 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7296 return false;
7297
7298 // If we've fallen outside of the end offset, just pretend there's nothing to
7299 // write to/read from.
7300 if (EndOffset <= LVal.getLValueOffset())
7301 Size = 0;
7302 else
7303 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7304 return true;
John McCall95007602010-05-10 23:27:23 +00007305}
7306
Peter Collingbournee9200682011-05-13 03:29:01 +00007307bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007308 if (unsigned BuiltinOp = E->getBuiltinCallee())
7309 return VisitBuiltinCallExpr(E, BuiltinOp);
7310
7311 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7312}
7313
7314bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7315 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007316 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007317 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007318 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007319
7320 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007321 // The type was checked when we built the expression.
7322 unsigned Type =
7323 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7324 assert(Type <= 3 && "unexpected type");
7325
George Burgess IVa7470272016-12-20 01:05:42 +00007326 uint64_t Size;
7327 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7328 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007329
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007330 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007331 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007332
Richard Smith01ade172012-05-23 04:13:20 +00007333 // Expression had no side effects, but we couldn't statically determine the
7334 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007335 switch (Info.EvalMode) {
7336 case EvalInfo::EM_ConstantExpression:
7337 case EvalInfo::EM_PotentialConstantExpression:
7338 case EvalInfo::EM_ConstantFold:
7339 case EvalInfo::EM_EvaluateForOverflow:
7340 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVa7470272016-12-20 01:05:42 +00007341 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007342 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007343 return Error(E);
7344 case EvalInfo::EM_ConstantExpressionUnevaluated:
7345 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007346 // Reduce it to a constant now.
7347 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007348 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007349
7350 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007351 }
7352
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007353 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007354 case Builtin::BI__builtin_bswap32:
7355 case Builtin::BI__builtin_bswap64: {
7356 APSInt Val;
7357 if (!EvaluateInteger(E->getArg(0), Val, Info))
7358 return false;
7359
7360 return Success(Val.byteSwap(), E);
7361 }
7362
Richard Smith8889a3d2013-06-13 06:26:32 +00007363 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007364 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007365
7366 // FIXME: BI__builtin_clrsb
7367 // FIXME: BI__builtin_clrsbl
7368 // FIXME: BI__builtin_clrsbll
7369
Richard Smith80b3c8e2013-06-13 05:04:16 +00007370 case Builtin::BI__builtin_clz:
7371 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007372 case Builtin::BI__builtin_clzll:
7373 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007374 APSInt Val;
7375 if (!EvaluateInteger(E->getArg(0), Val, Info))
7376 return false;
7377 if (!Val)
7378 return Error(E);
7379
7380 return Success(Val.countLeadingZeros(), E);
7381 }
7382
Richard Smith8889a3d2013-06-13 06:26:32 +00007383 case Builtin::BI__builtin_constant_p:
7384 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7385
Richard Smith80b3c8e2013-06-13 05:04:16 +00007386 case Builtin::BI__builtin_ctz:
7387 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007388 case Builtin::BI__builtin_ctzll:
7389 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007390 APSInt Val;
7391 if (!EvaluateInteger(E->getArg(0), Val, Info))
7392 return false;
7393 if (!Val)
7394 return Error(E);
7395
7396 return Success(Val.countTrailingZeros(), E);
7397 }
7398
Richard Smith8889a3d2013-06-13 06:26:32 +00007399 case Builtin::BI__builtin_eh_return_data_regno: {
7400 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7401 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7402 return Success(Operand, E);
7403 }
7404
7405 case Builtin::BI__builtin_expect:
7406 return Visit(E->getArg(0));
7407
7408 case Builtin::BI__builtin_ffs:
7409 case Builtin::BI__builtin_ffsl:
7410 case Builtin::BI__builtin_ffsll: {
7411 APSInt Val;
7412 if (!EvaluateInteger(E->getArg(0), Val, Info))
7413 return false;
7414
7415 unsigned N = Val.countTrailingZeros();
7416 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7417 }
7418
7419 case Builtin::BI__builtin_fpclassify: {
7420 APFloat Val(0.0);
7421 if (!EvaluateFloat(E->getArg(5), Val, Info))
7422 return false;
7423 unsigned Arg;
7424 switch (Val.getCategory()) {
7425 case APFloat::fcNaN: Arg = 0; break;
7426 case APFloat::fcInfinity: Arg = 1; break;
7427 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7428 case APFloat::fcZero: Arg = 4; break;
7429 }
7430 return Visit(E->getArg(Arg));
7431 }
7432
7433 case Builtin::BI__builtin_isinf_sign: {
7434 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007435 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007436 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7437 }
7438
Richard Smithea3019d2013-10-15 19:07:14 +00007439 case Builtin::BI__builtin_isinf: {
7440 APFloat Val(0.0);
7441 return EvaluateFloat(E->getArg(0), Val, Info) &&
7442 Success(Val.isInfinity() ? 1 : 0, E);
7443 }
7444
7445 case Builtin::BI__builtin_isfinite: {
7446 APFloat Val(0.0);
7447 return EvaluateFloat(E->getArg(0), Val, Info) &&
7448 Success(Val.isFinite() ? 1 : 0, E);
7449 }
7450
7451 case Builtin::BI__builtin_isnan: {
7452 APFloat Val(0.0);
7453 return EvaluateFloat(E->getArg(0), Val, Info) &&
7454 Success(Val.isNaN() ? 1 : 0, E);
7455 }
7456
7457 case Builtin::BI__builtin_isnormal: {
7458 APFloat Val(0.0);
7459 return EvaluateFloat(E->getArg(0), Val, Info) &&
7460 Success(Val.isNormal() ? 1 : 0, E);
7461 }
7462
Richard Smith8889a3d2013-06-13 06:26:32 +00007463 case Builtin::BI__builtin_parity:
7464 case Builtin::BI__builtin_parityl:
7465 case Builtin::BI__builtin_parityll: {
7466 APSInt Val;
7467 if (!EvaluateInteger(E->getArg(0), Val, Info))
7468 return false;
7469
7470 return Success(Val.countPopulation() % 2, E);
7471 }
7472
Richard Smith80b3c8e2013-06-13 05:04:16 +00007473 case Builtin::BI__builtin_popcount:
7474 case Builtin::BI__builtin_popcountl:
7475 case Builtin::BI__builtin_popcountll: {
7476 APSInt Val;
7477 if (!EvaluateInteger(E->getArg(0), Val, Info))
7478 return false;
7479
7480 return Success(Val.countPopulation(), E);
7481 }
7482
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007483 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007484 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007485 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007486 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007487 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007488 << /*isConstexpr*/0 << /*isConstructor*/0
7489 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007490 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007491 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007492 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007493 case Builtin::BI__builtin_strlen:
7494 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007495 // As an extension, we support __builtin_strlen() as a constant expression,
7496 // and support folding strlen() to a constant.
7497 LValue String;
7498 if (!EvaluatePointer(E->getArg(0), String, Info))
7499 return false;
7500
Richard Smith8110c9d2016-11-29 19:45:17 +00007501 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7502
Richard Smithe6c19f22013-11-15 02:10:04 +00007503 // Fast path: if it's a string literal, search the string value.
7504 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7505 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007506 // The string literal may have embedded null characters. Find the first
7507 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007508 StringRef Str = S->getBytes();
7509 int64_t Off = String.Offset.getQuantity();
7510 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007511 S->getCharByteWidth() == 1 &&
7512 // FIXME: Add fast-path for wchar_t too.
7513 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007514 Str = Str.substr(Off);
7515
7516 StringRef::size_type Pos = Str.find(0);
7517 if (Pos != StringRef::npos)
7518 Str = Str.substr(0, Pos);
7519
7520 return Success(Str.size(), E);
7521 }
7522
7523 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007524 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007525
7526 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007527 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7528 APValue Char;
7529 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7530 !Char.isInt())
7531 return false;
7532 if (!Char.getInt())
7533 return Success(Strlen, E);
7534 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7535 return false;
7536 }
7537 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007538
Richard Smithe151bab2016-11-11 23:43:35 +00007539 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007540 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007541 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007542 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007543 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007544 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007545 // A call to strlen is not a constant expression.
7546 if (Info.getLangOpts().CPlusPlus11)
7547 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7548 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007549 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007550 else
7551 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7552 // Fall through.
7553 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007554 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007555 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007556 case Builtin::BI__builtin_wcsncmp:
7557 case Builtin::BI__builtin_memcmp:
7558 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007559 LValue String1, String2;
7560 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7561 !EvaluatePointer(E->getArg(1), String2, Info))
7562 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007563
7564 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7565
Richard Smithe151bab2016-11-11 23:43:35 +00007566 uint64_t MaxLength = uint64_t(-1);
7567 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007568 BuiltinOp != Builtin::BIwcscmp &&
7569 BuiltinOp != Builtin::BI__builtin_strcmp &&
7570 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007571 APSInt N;
7572 if (!EvaluateInteger(E->getArg(2), N, Info))
7573 return false;
7574 MaxLength = N.getExtValue();
7575 }
7576 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007577 BuiltinOp != Builtin::BIwmemcmp &&
7578 BuiltinOp != Builtin::BI__builtin_memcmp &&
7579 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007580 for (; MaxLength; --MaxLength) {
7581 APValue Char1, Char2;
7582 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7583 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7584 !Char1.isInt() || !Char2.isInt())
7585 return false;
7586 if (Char1.getInt() != Char2.getInt())
7587 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7588 if (StopAtNull && !Char1.getInt())
7589 return Success(0, E);
7590 assert(!(StopAtNull && !Char2.getInt()));
7591 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7592 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7593 return false;
7594 }
7595 // We hit the strncmp / memcmp limit.
7596 return Success(0, E);
7597 }
7598
Richard Smith01ba47d2012-04-13 00:45:38 +00007599 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007600 case Builtin::BI__atomic_is_lock_free:
7601 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007602 APSInt SizeVal;
7603 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7604 return false;
7605
7606 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7607 // of two less than the maximum inline atomic width, we know it is
7608 // lock-free. If the size isn't a power of two, or greater than the
7609 // maximum alignment where we promote atomics, we know it is not lock-free
7610 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7611 // the answer can only be determined at runtime; for example, 16-byte
7612 // atomics have lock-free implementations on some, but not all,
7613 // x86-64 processors.
7614
7615 // Check power-of-two.
7616 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007617 if (Size.isPowerOfTwo()) {
7618 // Check against inlining width.
7619 unsigned InlineWidthBits =
7620 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7621 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7622 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7623 Size == CharUnits::One() ||
7624 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7625 Expr::NPC_NeverValueDependent))
7626 // OK, we will inline appropriately-aligned operations of this size,
7627 // and _Atomic(T) is appropriately-aligned.
7628 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007629
Richard Smith01ba47d2012-04-13 00:45:38 +00007630 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7631 castAs<PointerType>()->getPointeeType();
7632 if (!PointeeType->isIncompleteType() &&
7633 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7634 // OK, we will inline operations on this object.
7635 return Success(1, E);
7636 }
7637 }
7638 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007639
Richard Smith01ba47d2012-04-13 00:45:38 +00007640 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7641 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007642 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007643 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007644}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007645
Richard Smith8b3497e2011-10-31 01:37:14 +00007646static bool HasSameBase(const LValue &A, const LValue &B) {
7647 if (!A.getLValueBase())
7648 return !B.getLValueBase();
7649 if (!B.getLValueBase())
7650 return false;
7651
Richard Smithce40ad62011-11-12 22:28:03 +00007652 if (A.getLValueBase().getOpaqueValue() !=
7653 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007654 const Decl *ADecl = GetLValueBaseDecl(A);
7655 if (!ADecl)
7656 return false;
7657 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007658 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007659 return false;
7660 }
7661
7662 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007663 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007664}
7665
Richard Smithd20f1e62014-10-21 23:01:04 +00007666/// \brief Determine whether this is a pointer past the end of the complete
7667/// object referred to by the lvalue.
7668static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7669 const LValue &LV) {
7670 // A null pointer can be viewed as being "past the end" but we don't
7671 // choose to look at it that way here.
7672 if (!LV.getLValueBase())
7673 return false;
7674
7675 // If the designator is valid and refers to a subobject, we're not pointing
7676 // past the end.
7677 if (!LV.getLValueDesignator().Invalid &&
7678 !LV.getLValueDesignator().isOnePastTheEnd())
7679 return false;
7680
David Majnemerc378ca52015-08-29 08:32:55 +00007681 // A pointer to an incomplete type might be past-the-end if the type's size is
7682 // zero. We cannot tell because the type is incomplete.
7683 QualType Ty = getType(LV.getLValueBase());
7684 if (Ty->isIncompleteType())
7685 return true;
7686
Richard Smithd20f1e62014-10-21 23:01:04 +00007687 // We're a past-the-end pointer if we point to the byte after the object,
7688 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007689 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007690 return LV.getLValueOffset() == Size;
7691}
7692
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007693namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007694
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007695/// \brief Data recursive integer evaluator of certain binary operators.
7696///
7697/// We use a data recursive algorithm for binary operators so that we are able
7698/// to handle extreme cases of chained binary operators without causing stack
7699/// overflow.
7700class DataRecursiveIntBinOpEvaluator {
7701 struct EvalResult {
7702 APValue Val;
7703 bool Failed;
7704
7705 EvalResult() : Failed(false) { }
7706
7707 void swap(EvalResult &RHS) {
7708 Val.swap(RHS.Val);
7709 Failed = RHS.Failed;
7710 RHS.Failed = false;
7711 }
7712 };
7713
7714 struct Job {
7715 const Expr *E;
7716 EvalResult LHSResult; // meaningful only for binary operator expression.
7717 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007718
David Blaikie73726062015-08-12 23:09:24 +00007719 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007720 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007721
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007722 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007723 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007724 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007725
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007726 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007727 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007728 };
7729
7730 SmallVector<Job, 16> Queue;
7731
7732 IntExprEvaluator &IntEval;
7733 EvalInfo &Info;
7734 APValue &FinalResult;
7735
7736public:
7737 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7738 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7739
7740 /// \brief True if \param E is a binary operator that we are going to handle
7741 /// data recursively.
7742 /// We handle binary operators that are comma, logical, or that have operands
7743 /// with integral or enumeration type.
7744 static bool shouldEnqueue(const BinaryOperator *E) {
7745 return E->getOpcode() == BO_Comma ||
7746 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007747 (E->isRValue() &&
7748 E->getType()->isIntegralOrEnumerationType() &&
7749 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007750 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007751 }
7752
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007753 bool Traverse(const BinaryOperator *E) {
7754 enqueue(E);
7755 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007756 while (!Queue.empty())
7757 process(PrevResult);
7758
7759 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007760
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007761 FinalResult.swap(PrevResult.Val);
7762 return true;
7763 }
7764
7765private:
7766 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7767 return IntEval.Success(Value, E, Result);
7768 }
7769 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7770 return IntEval.Success(Value, E, Result);
7771 }
7772 bool Error(const Expr *E) {
7773 return IntEval.Error(E);
7774 }
7775 bool Error(const Expr *E, diag::kind D) {
7776 return IntEval.Error(E, D);
7777 }
7778
7779 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7780 return Info.CCEDiag(E, D);
7781 }
7782
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007783 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7784 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007785 bool &SuppressRHSDiags);
7786
7787 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7788 const BinaryOperator *E, APValue &Result);
7789
7790 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7791 Result.Failed = !Evaluate(Result.Val, Info, E);
7792 if (Result.Failed)
7793 Result.Val = APValue();
7794 }
7795
Richard Trieuba4d0872012-03-21 23:30:30 +00007796 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007797
7798 void enqueue(const Expr *E) {
7799 E = E->IgnoreParens();
7800 Queue.resize(Queue.size()+1);
7801 Queue.back().E = E;
7802 Queue.back().Kind = Job::AnyExprKind;
7803 }
7804};
7805
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007806}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007807
7808bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007809 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007810 bool &SuppressRHSDiags) {
7811 if (E->getOpcode() == BO_Comma) {
7812 // Ignore LHS but note if we could not evaluate it.
7813 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007814 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007815 return true;
7816 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007817
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007818 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007819 bool LHSAsBool;
7820 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007821 // We were able to evaluate the LHS, see if we can get away with not
7822 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007823 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7824 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007825 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007826 }
7827 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007828 LHSResult.Failed = true;
7829
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007830 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00007831 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007832 if (!Info.noteSideEffect())
7833 return false;
7834
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007835 // We can't evaluate the LHS; however, sometimes the result
7836 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7837 // Don't ignore RHS and suppress diagnostics from this arm.
7838 SuppressRHSDiags = true;
7839 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007840
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007841 return true;
7842 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007843
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007844 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7845 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007846
George Burgess IVa145e252016-05-25 22:38:36 +00007847 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007848 return false; // Ignore RHS;
7849
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007850 return true;
7851}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007852
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007853bool DataRecursiveIntBinOpEvaluator::
7854 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7855 const BinaryOperator *E, APValue &Result) {
7856 if (E->getOpcode() == BO_Comma) {
7857 if (RHSResult.Failed)
7858 return false;
7859 Result = RHSResult.Val;
7860 return true;
7861 }
7862
7863 if (E->isLogicalOp()) {
7864 bool lhsResult, rhsResult;
7865 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7866 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7867
7868 if (LHSIsOK) {
7869 if (RHSIsOK) {
7870 if (E->getOpcode() == BO_LOr)
7871 return Success(lhsResult || rhsResult, E, Result);
7872 else
7873 return Success(lhsResult && rhsResult, E, Result);
7874 }
7875 } else {
7876 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007877 // We can't evaluate the LHS; however, sometimes the result
7878 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7879 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007880 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007881 }
7882 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007883
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007884 return false;
7885 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007886
7887 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7888 E->getRHS()->getType()->isIntegralOrEnumerationType());
7889
7890 if (LHSResult.Failed || RHSResult.Failed)
7891 return false;
7892
7893 const APValue &LHSVal = LHSResult.Val;
7894 const APValue &RHSVal = RHSResult.Val;
7895
7896 // Handle cases like (unsigned long)&a + 4.
7897 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7898 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007899 CharUnits AdditionalOffset =
7900 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007901 if (E->getOpcode() == BO_Add)
7902 Result.getLValueOffset() += AdditionalOffset;
7903 else
7904 Result.getLValueOffset() -= AdditionalOffset;
7905 return true;
7906 }
7907
7908 // Handle cases like 4 + (unsigned long)&a
7909 if (E->getOpcode() == BO_Add &&
7910 RHSVal.isLValue() && LHSVal.isInt()) {
7911 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007912 Result.getLValueOffset() +=
7913 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007914 return true;
7915 }
7916
7917 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7918 // Handle (intptr_t)&&A - (intptr_t)&&B.
7919 if (!LHSVal.getLValueOffset().isZero() ||
7920 !RHSVal.getLValueOffset().isZero())
7921 return false;
7922 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7923 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7924 if (!LHSExpr || !RHSExpr)
7925 return false;
7926 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7927 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7928 if (!LHSAddrExpr || !RHSAddrExpr)
7929 return false;
7930 // Make sure both labels come from the same function.
7931 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7932 RHSAddrExpr->getLabel()->getDeclContext())
7933 return false;
7934 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7935 return true;
7936 }
Richard Smith43e77732013-05-07 04:50:00 +00007937
7938 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007939 if (!LHSVal.isInt() || !RHSVal.isInt())
7940 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00007941
7942 // Set up the width and signedness manually, in case it can't be deduced
7943 // from the operation we're performing.
7944 // FIXME: Don't do this in the cases where we can deduce it.
7945 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7946 E->getType()->isUnsignedIntegerOrEnumerationType());
7947 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7948 RHSVal.getInt(), Value))
7949 return false;
7950 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007951}
7952
Richard Trieuba4d0872012-03-21 23:30:30 +00007953void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007954 Job &job = Queue.back();
7955
7956 switch (job.Kind) {
7957 case Job::AnyExprKind: {
7958 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7959 if (shouldEnqueue(Bop)) {
7960 job.Kind = Job::BinOpKind;
7961 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007962 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007963 }
7964 }
7965
7966 EvaluateExpr(job.E, Result);
7967 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007968 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007969 }
7970
7971 case Job::BinOpKind: {
7972 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007973 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007974 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007975 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007976 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007977 }
7978 if (SuppressRHSDiags)
7979 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007980 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007981 job.Kind = Job::BinOpVisitedLHSKind;
7982 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007983 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007984 }
7985
7986 case Job::BinOpVisitedLHSKind: {
7987 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7988 EvalResult RHS;
7989 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00007990 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007991 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007992 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007993 }
7994 }
7995
7996 llvm_unreachable("Invalid Job::Kind!");
7997}
7998
George Burgess IV8c892b52016-05-25 22:31:54 +00007999namespace {
8000/// Used when we determine that we should fail, but can keep evaluating prior to
8001/// noting that we had a failure.
8002class DelayedNoteFailureRAII {
8003 EvalInfo &Info;
8004 bool NoteFailure;
8005
8006public:
8007 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8008 : Info(Info), NoteFailure(NoteFailure) {}
8009 ~DelayedNoteFailureRAII() {
8010 if (NoteFailure) {
8011 bool ContinueAfterFailure = Info.noteFailure();
8012 (void)ContinueAfterFailure;
8013 assert(ContinueAfterFailure &&
8014 "Shouldn't have kept evaluating on failure.");
8015 }
8016 }
8017};
8018}
8019
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008020bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008021 // We don't call noteFailure immediately because the assignment happens after
8022 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008023 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008024 return Error(E);
8025
George Burgess IV8c892b52016-05-25 22:31:54 +00008026 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008027 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8028 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008029
Anders Carlssonacc79812008-11-16 07:17:21 +00008030 QualType LHSTy = E->getLHS()->getType();
8031 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008032
Chandler Carruthb29a7432014-10-11 11:03:30 +00008033 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008034 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008035 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008036 if (E->isAssignmentOp()) {
8037 LValue LV;
8038 EvaluateLValue(E->getLHS(), LV, Info);
8039 LHSOK = false;
8040 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008041 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8042 if (LHSOK) {
8043 LHS.makeComplexFloat();
8044 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8045 }
8046 } else {
8047 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8048 }
George Burgess IVa145e252016-05-25 22:38:36 +00008049 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008050 return false;
8051
Chandler Carruthb29a7432014-10-11 11:03:30 +00008052 if (E->getRHS()->getType()->isRealFloatingType()) {
8053 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8054 return false;
8055 RHS.makeComplexFloat();
8056 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8057 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008058 return false;
8059
8060 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008061 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008062 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008063 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008064 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8065
John McCalle3027922010-08-25 11:45:40 +00008066 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008067 return Success((CR_r == APFloat::cmpEqual &&
8068 CR_i == APFloat::cmpEqual), E);
8069 else {
John McCalle3027922010-08-25 11:45:40 +00008070 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008071 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008072 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008073 CR_r == APFloat::cmpLessThan ||
8074 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008075 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008076 CR_i == APFloat::cmpLessThan ||
8077 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008078 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008079 } else {
John McCalle3027922010-08-25 11:45:40 +00008080 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008081 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8082 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8083 else {
John McCalle3027922010-08-25 11:45:40 +00008084 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008085 "Invalid compex comparison.");
8086 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8087 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8088 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008089 }
8090 }
Mike Stump11289f42009-09-09 15:08:12 +00008091
Anders Carlssonacc79812008-11-16 07:17:21 +00008092 if (LHSTy->isRealFloatingType() &&
8093 RHSTy->isRealFloatingType()) {
8094 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008095
Richard Smith253c2a32012-01-27 01:14:48 +00008096 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008097 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008098 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008099
Richard Smith253c2a32012-01-27 01:14:48 +00008100 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008101 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008102
Anders Carlssonacc79812008-11-16 07:17:21 +00008103 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008104
Anders Carlssonacc79812008-11-16 07:17:21 +00008105 switch (E->getOpcode()) {
8106 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008107 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008108 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008109 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008110 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008111 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008112 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008113 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008114 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008115 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008116 E);
John McCalle3027922010-08-25 11:45:40 +00008117 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008118 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008119 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008120 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008121 || CR == APFloat::cmpLessThan
8122 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008123 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008124 }
Mike Stump11289f42009-09-09 15:08:12 +00008125
Eli Friedmana38da572009-04-28 19:17:36 +00008126 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008127 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008128 LValue LHSValue, RHSValue;
8129
8130 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008131 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008132 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008133
Richard Smith253c2a32012-01-27 01:14:48 +00008134 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008135 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008136
Richard Smith8b3497e2011-10-31 01:37:14 +00008137 // Reject differing bases from the normal codepath; we special-case
8138 // comparisons to null.
8139 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008140 if (E->getOpcode() == BO_Sub) {
8141 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008142 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008143 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008144 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008145 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008146 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008147 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008148 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8149 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8150 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008151 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008152 // Make sure both labels come from the same function.
8153 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8154 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008155 return Error(E);
8156 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008157 }
Richard Smith83c68212011-10-31 05:11:32 +00008158 // Inequalities and subtractions between unrelated pointers have
8159 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008160 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008161 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008162 // A constant address may compare equal to the address of a symbol.
8163 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008164 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008165 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8166 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008167 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008168 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008169 // distinct addresses. In clang, the result of such a comparison is
8170 // unspecified, so it is not a constant expression. However, we do know
8171 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008172 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8173 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008174 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008175 // We can't tell whether weak symbols will end up pointing to the same
8176 // object.
8177 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008178 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008179 // We can't compare the address of the start of one object with the
8180 // past-the-end address of another object, per C++ DR1652.
8181 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8182 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8183 (RHSValue.Base && RHSValue.Offset.isZero() &&
8184 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8185 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008186 // We can't tell whether an object is at the same address as another
8187 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008188 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8189 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008190 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008191 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008192 // (Note that clang defaults to -fmerge-all-constants, which can
8193 // lead to inconsistent results for comparisons involving the address
8194 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008195 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008196 }
Eli Friedman64004332009-03-23 04:38:34 +00008197
Richard Smith1b470412012-02-01 08:10:20 +00008198 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8199 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8200
Richard Smith84f6dcf2012-02-02 01:16:57 +00008201 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8202 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8203
John McCalle3027922010-08-25 11:45:40 +00008204 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008205 // C++11 [expr.add]p6:
8206 // Unless both pointers point to elements of the same array object, or
8207 // one past the last element of the array object, the behavior is
8208 // undefined.
8209 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8210 !AreElementsOfSameArray(getType(LHSValue.Base),
8211 LHSDesignator, RHSDesignator))
8212 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8213
Chris Lattner882bdf22010-04-20 17:13:14 +00008214 QualType Type = E->getLHS()->getType();
8215 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008216
Richard Smithd62306a2011-11-10 06:34:14 +00008217 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008218 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008219 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008220
Richard Smith84c6b3d2013-09-10 21:34:14 +00008221 // As an extension, a type may have zero size (empty struct or union in
8222 // C, array of zero length). Pointer subtraction in such cases has
8223 // undefined behavior, so is not constant.
8224 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008225 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008226 << ElementType;
8227 return false;
8228 }
8229
Richard Smith1b470412012-02-01 08:10:20 +00008230 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8231 // and produce incorrect results when it overflows. Such behavior
8232 // appears to be non-conforming, but is common, so perhaps we should
8233 // assume the standard intended for such cases to be undefined behavior
8234 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008235
Richard Smith1b470412012-02-01 08:10:20 +00008236 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8237 // overflow in the final conversion to ptrdiff_t.
8238 APSInt LHS(
8239 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8240 APSInt RHS(
8241 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8242 APSInt ElemSize(
8243 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8244 APSInt TrueResult = (LHS - RHS) / ElemSize;
8245 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8246
Richard Smith0c6124b2015-12-03 01:36:22 +00008247 if (Result.extend(65) != TrueResult &&
8248 !HandleOverflow(Info, E, TrueResult, E->getType()))
8249 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008250 return Success(Result, E);
8251 }
Richard Smithde21b242012-01-31 06:41:30 +00008252
8253 // C++11 [expr.rel]p3:
8254 // Pointers to void (after pointer conversions) can be compared, with a
8255 // result defined as follows: If both pointers represent the same
8256 // address or are both the null pointer value, the result is true if the
8257 // operator is <= or >= and false otherwise; otherwise the result is
8258 // unspecified.
8259 // We interpret this as applying to pointers to *cv* void.
8260 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008261 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008262 CCEDiag(E, diag::note_constexpr_void_comparison);
8263
Richard Smith84f6dcf2012-02-02 01:16:57 +00008264 // C++11 [expr.rel]p2:
8265 // - If two pointers point to non-static data members of the same object,
8266 // or to subobjects or array elements fo such members, recursively, the
8267 // pointer to the later declared member compares greater provided the
8268 // two members have the same access control and provided their class is
8269 // not a union.
8270 // [...]
8271 // - Otherwise pointer comparisons are unspecified.
8272 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8273 E->isRelationalOp()) {
8274 bool WasArrayIndex;
8275 unsigned Mismatch =
8276 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8277 RHSDesignator, WasArrayIndex);
8278 // At the point where the designators diverge, the comparison has a
8279 // specified value if:
8280 // - we are comparing array indices
8281 // - we are comparing fields of a union, or fields with the same access
8282 // Otherwise, the result is unspecified and thus the comparison is not a
8283 // constant expression.
8284 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8285 Mismatch < RHSDesignator.Entries.size()) {
8286 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8287 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8288 if (!LF && !RF)
8289 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8290 else if (!LF)
8291 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8292 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8293 << RF->getParent() << RF;
8294 else if (!RF)
8295 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8296 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8297 << LF->getParent() << LF;
8298 else if (!LF->getParent()->isUnion() &&
8299 LF->getAccess() != RF->getAccess())
8300 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8301 << LF << LF->getAccess() << RF << RF->getAccess()
8302 << LF->getParent();
8303 }
8304 }
8305
Eli Friedman6c31cb42012-04-16 04:30:08 +00008306 // The comparison here must be unsigned, and performed with the same
8307 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008308 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8309 uint64_t CompareLHS = LHSOffset.getQuantity();
8310 uint64_t CompareRHS = RHSOffset.getQuantity();
8311 assert(PtrSize <= 64 && "Unexpected pointer width");
8312 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8313 CompareLHS &= Mask;
8314 CompareRHS &= Mask;
8315
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008316 // If there is a base and this is a relational operator, we can only
8317 // compare pointers within the object in question; otherwise, the result
8318 // depends on where the object is located in memory.
8319 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8320 QualType BaseTy = getType(LHSValue.Base);
8321 if (BaseTy->isIncompleteType())
8322 return Error(E);
8323 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8324 uint64_t OffsetLimit = Size.getQuantity();
8325 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8326 return Error(E);
8327 }
8328
Richard Smith8b3497e2011-10-31 01:37:14 +00008329 switch (E->getOpcode()) {
8330 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008331 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8332 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8333 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8334 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8335 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8336 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008337 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008338 }
8339 }
Richard Smith7bb00672012-02-01 01:42:44 +00008340
8341 if (LHSTy->isMemberPointerType()) {
8342 assert(E->isEqualityOp() && "unexpected member pointer operation");
8343 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8344
8345 MemberPtr LHSValue, RHSValue;
8346
8347 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008348 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008349 return false;
8350
8351 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8352 return false;
8353
8354 // C++11 [expr.eq]p2:
8355 // If both operands are null, they compare equal. Otherwise if only one is
8356 // null, they compare unequal.
8357 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8358 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8359 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8360 }
8361
8362 // Otherwise if either is a pointer to a virtual member function, the
8363 // result is unspecified.
8364 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8365 if (MD->isVirtual())
8366 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8367 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8368 if (MD->isVirtual())
8369 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8370
8371 // Otherwise they compare equal if and only if they would refer to the
8372 // same member of the same most derived object or the same subobject if
8373 // they were dereferenced with a hypothetical object of the associated
8374 // class type.
8375 bool Equal = LHSValue == RHSValue;
8376 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8377 }
8378
Richard Smithab44d9b2012-02-14 22:35:28 +00008379 if (LHSTy->isNullPtrType()) {
8380 assert(E->isComparisonOp() && "unexpected nullptr operation");
8381 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8382 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8383 // are compared, the result is true of the operator is <=, >= or ==, and
8384 // false otherwise.
8385 BinaryOperator::Opcode Opcode = E->getOpcode();
8386 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8387 }
8388
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008389 assert((!LHSTy->isIntegralOrEnumerationType() ||
8390 !RHSTy->isIntegralOrEnumerationType()) &&
8391 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8392 // We can't continue from here for non-integral types.
8393 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008394}
8395
Peter Collingbournee190dee2011-03-11 19:24:49 +00008396/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8397/// a result as the expression's type.
8398bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8399 const UnaryExprOrTypeTraitExpr *E) {
8400 switch(E->getKind()) {
8401 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008402 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008403 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008404 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008405 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008406 }
Eli Friedman64004332009-03-23 04:38:34 +00008407
Peter Collingbournee190dee2011-03-11 19:24:49 +00008408 case UETT_VecStep: {
8409 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008410
Peter Collingbournee190dee2011-03-11 19:24:49 +00008411 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008412 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008413
Peter Collingbournee190dee2011-03-11 19:24:49 +00008414 // The vec_step built-in functions that take a 3-component
8415 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8416 if (n == 3)
8417 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008418
Peter Collingbournee190dee2011-03-11 19:24:49 +00008419 return Success(n, E);
8420 } else
8421 return Success(1, E);
8422 }
8423
8424 case UETT_SizeOf: {
8425 QualType SrcTy = E->getTypeOfArgument();
8426 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8427 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008428 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8429 SrcTy = Ref->getPointeeType();
8430
Richard Smithd62306a2011-11-10 06:34:14 +00008431 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008432 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008433 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008434 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008435 }
Alexey Bataev00396512015-07-02 03:40:19 +00008436 case UETT_OpenMPRequiredSimdAlign:
8437 assert(E->isArgumentType());
8438 return Success(
8439 Info.Ctx.toCharUnitsFromBits(
8440 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8441 .getQuantity(),
8442 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008443 }
8444
8445 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008446}
8447
Peter Collingbournee9200682011-05-13 03:29:01 +00008448bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008449 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008450 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008451 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008452 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008453 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008454 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008455 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008456 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008457 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008458 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008459 APSInt IdxResult;
8460 if (!EvaluateInteger(Idx, IdxResult, Info))
8461 return false;
8462 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8463 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008464 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008465 CurrentType = AT->getElementType();
8466 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8467 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008468 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008469 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008470
James Y Knight7281c352015-12-29 22:31:18 +00008471 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008472 FieldDecl *MemberDecl = ON.getField();
8473 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008474 if (!RT)
8475 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008476 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008477 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008478 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008479 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008480 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008481 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008482 CurrentType = MemberDecl->getType().getNonReferenceType();
8483 break;
8484 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008485
James Y Knight7281c352015-12-29 22:31:18 +00008486 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008487 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008488
James Y Knight7281c352015-12-29 22:31:18 +00008489 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008490 CXXBaseSpecifier *BaseSpec = ON.getBase();
8491 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008492 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008493
8494 // Find the layout of the class whose base we are looking into.
8495 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008496 if (!RT)
8497 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008498 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008499 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008500 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8501
8502 // Find the base class itself.
8503 CurrentType = BaseSpec->getType();
8504 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8505 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008506 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008507
8508 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008509 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008510 break;
8511 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008512 }
8513 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008514 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008515}
8516
Chris Lattnere13042c2008-07-11 19:10:17 +00008517bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008518 switch (E->getOpcode()) {
8519 default:
8520 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8521 // See C99 6.6p3.
8522 return Error(E);
8523 case UO_Extension:
8524 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8525 // If so, we could clear the diagnostic ID.
8526 return Visit(E->getSubExpr());
8527 case UO_Plus:
8528 // The result is just the value.
8529 return Visit(E->getSubExpr());
8530 case UO_Minus: {
8531 if (!Visit(E->getSubExpr()))
8532 return false;
8533 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008534 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008535 if (Value.isSigned() && Value.isMinSignedValue() &&
8536 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8537 E->getType()))
8538 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008539 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008540 }
8541 case UO_Not: {
8542 if (!Visit(E->getSubExpr()))
8543 return false;
8544 if (!Result.isInt()) return Error(E);
8545 return Success(~Result.getInt(), E);
8546 }
8547 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008548 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008549 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008550 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008551 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008552 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008553 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008554}
Mike Stump11289f42009-09-09 15:08:12 +00008555
Chris Lattner477c4be2008-07-12 01:15:53 +00008556/// HandleCast - This is used to evaluate implicit or explicit casts where the
8557/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008558bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8559 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008560 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008561 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008562
Eli Friedmanc757de22011-03-25 00:43:55 +00008563 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008564 case CK_BaseToDerived:
8565 case CK_DerivedToBase:
8566 case CK_UncheckedDerivedToBase:
8567 case CK_Dynamic:
8568 case CK_ToUnion:
8569 case CK_ArrayToPointerDecay:
8570 case CK_FunctionToPointerDecay:
8571 case CK_NullToPointer:
8572 case CK_NullToMemberPointer:
8573 case CK_BaseToDerivedMemberPointer:
8574 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008575 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008576 case CK_ConstructorConversion:
8577 case CK_IntegralToPointer:
8578 case CK_ToVoid:
8579 case CK_VectorSplat:
8580 case CK_IntegralToFloating:
8581 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008582 case CK_CPointerToObjCPointerCast:
8583 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008584 case CK_AnyPointerToBlockPointerCast:
8585 case CK_ObjCObjectLValueCast:
8586 case CK_FloatingRealToComplex:
8587 case CK_FloatingComplexToReal:
8588 case CK_FloatingComplexCast:
8589 case CK_FloatingComplexToIntegralComplex:
8590 case CK_IntegralRealToComplex:
8591 case CK_IntegralComplexCast:
8592 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008593 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008594 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008595 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008596 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008597 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008598 llvm_unreachable("invalid cast kind for integral value");
8599
Eli Friedman9faf2f92011-03-25 19:07:11 +00008600 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008601 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008602 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008603 case CK_ARCProduceObject:
8604 case CK_ARCConsumeObject:
8605 case CK_ARCReclaimReturnedObject:
8606 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008607 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008608 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008609
Richard Smith4ef685b2012-01-17 21:17:26 +00008610 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008611 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008612 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008613 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008614 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008615
8616 case CK_MemberPointerToBoolean:
8617 case CK_PointerToBoolean:
8618 case CK_IntegralToBoolean:
8619 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008620 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008621 case CK_FloatingComplexToBoolean:
8622 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008623 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008624 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008625 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008626 uint64_t IntResult = BoolResult;
8627 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8628 IntResult = (uint64_t)-1;
8629 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008630 }
8631
Eli Friedmanc757de22011-03-25 00:43:55 +00008632 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008633 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008634 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008635
Eli Friedman742421e2009-02-20 01:15:07 +00008636 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008637 // Allow casts of address-of-label differences if they are no-ops
8638 // or narrowing. (The narrowing case isn't actually guaranteed to
8639 // be constant-evaluatable except in some narrow cases which are hard
8640 // to detect here. We let it through on the assumption the user knows
8641 // what they are doing.)
8642 if (Result.isAddrLabelDiff())
8643 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008644 // Only allow casts of lvalues if they are lossless.
8645 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8646 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008647
Richard Smith911e1422012-01-30 22:27:01 +00008648 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8649 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008650 }
Mike Stump11289f42009-09-09 15:08:12 +00008651
Eli Friedmanc757de22011-03-25 00:43:55 +00008652 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008653 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8654
John McCall45d55e42010-05-07 21:00:08 +00008655 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008656 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008657 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008658
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008659 if (LV.getLValueBase()) {
8660 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008661 // FIXME: Allow a larger integer size than the pointer size, and allow
8662 // narrowing back down to pointer width in subsequent integral casts.
8663 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008664 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008665 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008666
Richard Smithcf74da72011-11-16 07:18:12 +00008667 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008668 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008669 return true;
8670 }
8671
Yaxun Liu402804b2016-12-15 08:09:08 +00008672 uint64_t V;
8673 if (LV.isNullPointer())
8674 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8675 else
8676 V = LV.getLValueOffset().getQuantity();
8677
8678 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008679 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008680 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008681
Eli Friedmanc757de22011-03-25 00:43:55 +00008682 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008683 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008684 if (!EvaluateComplex(SubExpr, C, Info))
8685 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008686 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008687 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008688
Eli Friedmanc757de22011-03-25 00:43:55 +00008689 case CK_FloatingToIntegral: {
8690 APFloat F(0.0);
8691 if (!EvaluateFloat(SubExpr, F, Info))
8692 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008693
Richard Smith357362d2011-12-13 06:39:58 +00008694 APSInt Value;
8695 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8696 return false;
8697 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008698 }
8699 }
Mike Stump11289f42009-09-09 15:08:12 +00008700
Eli Friedmanc757de22011-03-25 00:43:55 +00008701 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008702}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008703
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008704bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8705 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008706 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008707 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8708 return false;
8709 if (!LV.isComplexInt())
8710 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008711 return Success(LV.getComplexIntReal(), E);
8712 }
8713
8714 return Visit(E->getSubExpr());
8715}
8716
Eli Friedman4e7a2412009-02-27 04:45:43 +00008717bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008718 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008719 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008720 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8721 return false;
8722 if (!LV.isComplexInt())
8723 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008724 return Success(LV.getComplexIntImag(), E);
8725 }
8726
Richard Smith4a678122011-10-24 18:44:57 +00008727 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008728 return Success(0, E);
8729}
8730
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008731bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8732 return Success(E->getPackLength(), E);
8733}
8734
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008735bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8736 return Success(E->getValue(), E);
8737}
8738
Chris Lattner05706e882008-07-11 18:11:29 +00008739//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008740// Float Evaluation
8741//===----------------------------------------------------------------------===//
8742
8743namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008744class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008745 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008746 APFloat &Result;
8747public:
8748 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008749 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008750
Richard Smith2e312c82012-03-03 22:46:17 +00008751 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008752 Result = V.getFloat();
8753 return true;
8754 }
Eli Friedman24c01542008-08-22 00:06:13 +00008755
Richard Smithfddd3842011-12-30 21:15:51 +00008756 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008757 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8758 return true;
8759 }
8760
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008761 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008762
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008763 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008764 bool VisitBinaryOperator(const BinaryOperator *E);
8765 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008766 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008767
John McCallb1fb0d32010-05-07 22:08:54 +00008768 bool VisitUnaryReal(const UnaryOperator *E);
8769 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008770
Richard Smithfddd3842011-12-30 21:15:51 +00008771 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008772};
8773} // end anonymous namespace
8774
8775static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008776 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008777 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008778}
8779
Jay Foad39c79802011-01-12 09:06:06 +00008780static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008781 QualType ResultTy,
8782 const Expr *Arg,
8783 bool SNaN,
8784 llvm::APFloat &Result) {
8785 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8786 if (!S) return false;
8787
8788 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8789
8790 llvm::APInt fill;
8791
8792 // Treat empty strings as if they were zero.
8793 if (S->getString().empty())
8794 fill = llvm::APInt(32, 0);
8795 else if (S->getString().getAsInteger(0, fill))
8796 return false;
8797
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008798 if (Context.getTargetInfo().isNan2008()) {
8799 if (SNaN)
8800 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8801 else
8802 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8803 } else {
8804 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8805 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8806 // a different encoding to what became a standard in 2008, and for pre-
8807 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8808 // sNaN. This is now known as "legacy NaN" encoding.
8809 if (SNaN)
8810 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8811 else
8812 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8813 }
8814
John McCall16291492010-02-28 13:00:19 +00008815 return true;
8816}
8817
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008818bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008819 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008820 default:
8821 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8822
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008823 case Builtin::BI__builtin_huge_val:
8824 case Builtin::BI__builtin_huge_valf:
8825 case Builtin::BI__builtin_huge_vall:
8826 case Builtin::BI__builtin_inf:
8827 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008828 case Builtin::BI__builtin_infl: {
8829 const llvm::fltSemantics &Sem =
8830 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008831 Result = llvm::APFloat::getInf(Sem);
8832 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008833 }
Mike Stump11289f42009-09-09 15:08:12 +00008834
John McCall16291492010-02-28 13:00:19 +00008835 case Builtin::BI__builtin_nans:
8836 case Builtin::BI__builtin_nansf:
8837 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008838 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8839 true, Result))
8840 return Error(E);
8841 return true;
John McCall16291492010-02-28 13:00:19 +00008842
Chris Lattner0b7282e2008-10-06 06:31:58 +00008843 case Builtin::BI__builtin_nan:
8844 case Builtin::BI__builtin_nanf:
8845 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008846 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008847 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008848 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8849 false, Result))
8850 return Error(E);
8851 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008852
8853 case Builtin::BI__builtin_fabs:
8854 case Builtin::BI__builtin_fabsf:
8855 case Builtin::BI__builtin_fabsl:
8856 if (!EvaluateFloat(E->getArg(0), Result, Info))
8857 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008858
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008859 if (Result.isNegative())
8860 Result.changeSign();
8861 return true;
8862
Richard Smith8889a3d2013-06-13 06:26:32 +00008863 // FIXME: Builtin::BI__builtin_powi
8864 // FIXME: Builtin::BI__builtin_powif
8865 // FIXME: Builtin::BI__builtin_powil
8866
Mike Stump11289f42009-09-09 15:08:12 +00008867 case Builtin::BI__builtin_copysign:
8868 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008869 case Builtin::BI__builtin_copysignl: {
8870 APFloat RHS(0.);
8871 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8872 !EvaluateFloat(E->getArg(1), RHS, Info))
8873 return false;
8874 Result.copySign(RHS);
8875 return true;
8876 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008877 }
8878}
8879
John McCallb1fb0d32010-05-07 22:08:54 +00008880bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008881 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8882 ComplexValue CV;
8883 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8884 return false;
8885 Result = CV.FloatReal;
8886 return true;
8887 }
8888
8889 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00008890}
8891
8892bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008893 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8894 ComplexValue CV;
8895 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8896 return false;
8897 Result = CV.FloatImag;
8898 return true;
8899 }
8900
Richard Smith4a678122011-10-24 18:44:57 +00008901 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00008902 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8903 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00008904 return true;
8905}
8906
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008907bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008908 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008909 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008910 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00008911 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00008912 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00008913 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8914 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008915 Result.changeSign();
8916 return true;
8917 }
8918}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008919
Eli Friedman24c01542008-08-22 00:06:13 +00008920bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008921 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8922 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00008923
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008924 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00008925 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008926 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00008927 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00008928 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8929 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00008930}
8931
8932bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8933 Result = E->getValue();
8934 return true;
8935}
8936
Peter Collingbournee9200682011-05-13 03:29:01 +00008937bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8938 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00008939
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008940 switch (E->getCastKind()) {
8941 default:
Richard Smith11562c52011-10-28 17:51:58 +00008942 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008943
8944 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008945 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00008946 return EvaluateInteger(SubExpr, IntResult, Info) &&
8947 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8948 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008949 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008950
8951 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008952 if (!Visit(SubExpr))
8953 return false;
Richard Smith357362d2011-12-13 06:39:58 +00008954 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8955 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008956 }
John McCalld7646252010-11-14 08:17:51 +00008957
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008958 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00008959 ComplexValue V;
8960 if (!EvaluateComplex(SubExpr, V, Info))
8961 return false;
8962 Result = V.getComplexFloatReal();
8963 return true;
8964 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008965 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008966}
8967
Eli Friedman24c01542008-08-22 00:06:13 +00008968//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008969// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00008970//===----------------------------------------------------------------------===//
8971
8972namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008973class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008974 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00008975 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00008976
Anders Carlsson537969c2008-11-16 20:27:53 +00008977public:
John McCall93d91dc2010-05-07 17:22:02 +00008978 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008979 : ExprEvaluatorBaseTy(info), Result(Result) {}
8980
Richard Smith2e312c82012-03-03 22:46:17 +00008981 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008982 Result.setFrom(V);
8983 return true;
8984 }
Mike Stump11289f42009-09-09 15:08:12 +00008985
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008986 bool ZeroInitialization(const Expr *E);
8987
Anders Carlsson537969c2008-11-16 20:27:53 +00008988 //===--------------------------------------------------------------------===//
8989 // Visitor Methods
8990 //===--------------------------------------------------------------------===//
8991
Peter Collingbournee9200682011-05-13 03:29:01 +00008992 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008993 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00008994 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008995 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008996 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008997};
8998} // end anonymous namespace
8999
John McCall93d91dc2010-05-07 17:22:02 +00009000static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9001 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009002 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009003 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009004}
9005
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009006bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009007 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009008 if (ElemTy->isRealFloatingType()) {
9009 Result.makeComplexFloat();
9010 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9011 Result.FloatReal = Zero;
9012 Result.FloatImag = Zero;
9013 } else {
9014 Result.makeComplexInt();
9015 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9016 Result.IntReal = Zero;
9017 Result.IntImag = Zero;
9018 }
9019 return true;
9020}
9021
Peter Collingbournee9200682011-05-13 03:29:01 +00009022bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9023 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009024
9025 if (SubExpr->getType()->isRealFloatingType()) {
9026 Result.makeComplexFloat();
9027 APFloat &Imag = Result.FloatImag;
9028 if (!EvaluateFloat(SubExpr, Imag, Info))
9029 return false;
9030
9031 Result.FloatReal = APFloat(Imag.getSemantics());
9032 return true;
9033 } else {
9034 assert(SubExpr->getType()->isIntegerType() &&
9035 "Unexpected imaginary literal.");
9036
9037 Result.makeComplexInt();
9038 APSInt &Imag = Result.IntImag;
9039 if (!EvaluateInteger(SubExpr, Imag, Info))
9040 return false;
9041
9042 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9043 return true;
9044 }
9045}
9046
Peter Collingbournee9200682011-05-13 03:29:01 +00009047bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009048
John McCallfcef3cf2010-12-14 17:51:41 +00009049 switch (E->getCastKind()) {
9050 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009051 case CK_BaseToDerived:
9052 case CK_DerivedToBase:
9053 case CK_UncheckedDerivedToBase:
9054 case CK_Dynamic:
9055 case CK_ToUnion:
9056 case CK_ArrayToPointerDecay:
9057 case CK_FunctionToPointerDecay:
9058 case CK_NullToPointer:
9059 case CK_NullToMemberPointer:
9060 case CK_BaseToDerivedMemberPointer:
9061 case CK_DerivedToBaseMemberPointer:
9062 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009063 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009064 case CK_ConstructorConversion:
9065 case CK_IntegralToPointer:
9066 case CK_PointerToIntegral:
9067 case CK_PointerToBoolean:
9068 case CK_ToVoid:
9069 case CK_VectorSplat:
9070 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009071 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009072 case CK_IntegralToBoolean:
9073 case CK_IntegralToFloating:
9074 case CK_FloatingToIntegral:
9075 case CK_FloatingToBoolean:
9076 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009077 case CK_CPointerToObjCPointerCast:
9078 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009079 case CK_AnyPointerToBlockPointerCast:
9080 case CK_ObjCObjectLValueCast:
9081 case CK_FloatingComplexToReal:
9082 case CK_FloatingComplexToBoolean:
9083 case CK_IntegralComplexToReal:
9084 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009085 case CK_ARCProduceObject:
9086 case CK_ARCConsumeObject:
9087 case CK_ARCReclaimReturnedObject:
9088 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009089 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009090 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009091 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00009092 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009093 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009094 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009095 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009096
John McCallfcef3cf2010-12-14 17:51:41 +00009097 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009098 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009099 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009100 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009101
9102 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009103 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009104 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009105 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009106
9107 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009108 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009109 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009110 return false;
9111
John McCallfcef3cf2010-12-14 17:51:41 +00009112 Result.makeComplexFloat();
9113 Result.FloatImag = APFloat(Real.getSemantics());
9114 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009115 }
9116
John McCallfcef3cf2010-12-14 17:51:41 +00009117 case CK_FloatingComplexCast: {
9118 if (!Visit(E->getSubExpr()))
9119 return false;
9120
9121 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9122 QualType From
9123 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9124
Richard Smith357362d2011-12-13 06:39:58 +00009125 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9126 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009127 }
9128
9129 case CK_FloatingComplexToIntegralComplex: {
9130 if (!Visit(E->getSubExpr()))
9131 return false;
9132
9133 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9134 QualType From
9135 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9136 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009137 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9138 To, Result.IntReal) &&
9139 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9140 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009141 }
9142
9143 case CK_IntegralRealToComplex: {
9144 APSInt &Real = Result.IntReal;
9145 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9146 return false;
9147
9148 Result.makeComplexInt();
9149 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9150 return true;
9151 }
9152
9153 case CK_IntegralComplexCast: {
9154 if (!Visit(E->getSubExpr()))
9155 return false;
9156
9157 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9158 QualType From
9159 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9160
Richard Smith911e1422012-01-30 22:27:01 +00009161 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9162 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009163 return true;
9164 }
9165
9166 case CK_IntegralComplexToFloatingComplex: {
9167 if (!Visit(E->getSubExpr()))
9168 return false;
9169
Ted Kremenek28831752012-08-23 20:46:57 +00009170 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009171 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009172 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009173 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009174 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9175 To, Result.FloatReal) &&
9176 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9177 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009178 }
9179 }
9180
9181 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009182}
9183
John McCall93d91dc2010-05-07 17:22:02 +00009184bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009185 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009186 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9187
Chandler Carrutha216cad2014-10-11 00:57:18 +00009188 // Track whether the LHS or RHS is real at the type system level. When this is
9189 // the case we can simplify our evaluation strategy.
9190 bool LHSReal = false, RHSReal = false;
9191
9192 bool LHSOK;
9193 if (E->getLHS()->getType()->isRealFloatingType()) {
9194 LHSReal = true;
9195 APFloat &Real = Result.FloatReal;
9196 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9197 if (LHSOK) {
9198 Result.makeComplexFloat();
9199 Result.FloatImag = APFloat(Real.getSemantics());
9200 }
9201 } else {
9202 LHSOK = Visit(E->getLHS());
9203 }
George Burgess IVa145e252016-05-25 22:38:36 +00009204 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009205 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009206
John McCall93d91dc2010-05-07 17:22:02 +00009207 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009208 if (E->getRHS()->getType()->isRealFloatingType()) {
9209 RHSReal = true;
9210 APFloat &Real = RHS.FloatReal;
9211 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9212 return false;
9213 RHS.makeComplexFloat();
9214 RHS.FloatImag = APFloat(Real.getSemantics());
9215 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009216 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009217
Chandler Carrutha216cad2014-10-11 00:57:18 +00009218 assert(!(LHSReal && RHSReal) &&
9219 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009220 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009221 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009222 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009223 if (Result.isComplexFloat()) {
9224 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9225 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009226 if (LHSReal)
9227 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9228 else if (!RHSReal)
9229 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9230 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009231 } else {
9232 Result.getComplexIntReal() += RHS.getComplexIntReal();
9233 Result.getComplexIntImag() += RHS.getComplexIntImag();
9234 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009235 break;
John McCalle3027922010-08-25 11:45:40 +00009236 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009237 if (Result.isComplexFloat()) {
9238 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9239 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009240 if (LHSReal) {
9241 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9242 Result.getComplexFloatImag().changeSign();
9243 } else if (!RHSReal) {
9244 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9245 APFloat::rmNearestTiesToEven);
9246 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009247 } else {
9248 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9249 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9250 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009251 break;
John McCalle3027922010-08-25 11:45:40 +00009252 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009253 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009254 // This is an implementation of complex multiplication according to the
9255 // constraints laid out in C11 Annex G. The implemantion uses the
9256 // following naming scheme:
9257 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009258 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009259 APFloat &A = LHS.getComplexFloatReal();
9260 APFloat &B = LHS.getComplexFloatImag();
9261 APFloat &C = RHS.getComplexFloatReal();
9262 APFloat &D = RHS.getComplexFloatImag();
9263 APFloat &ResR = Result.getComplexFloatReal();
9264 APFloat &ResI = Result.getComplexFloatImag();
9265 if (LHSReal) {
9266 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9267 ResR = A * C;
9268 ResI = A * D;
9269 } else if (RHSReal) {
9270 ResR = C * A;
9271 ResI = C * B;
9272 } else {
9273 // In the fully general case, we need to handle NaNs and infinities
9274 // robustly.
9275 APFloat AC = A * C;
9276 APFloat BD = B * D;
9277 APFloat AD = A * D;
9278 APFloat BC = B * C;
9279 ResR = AC - BD;
9280 ResI = AD + BC;
9281 if (ResR.isNaN() && ResI.isNaN()) {
9282 bool Recalc = false;
9283 if (A.isInfinity() || B.isInfinity()) {
9284 A = APFloat::copySign(
9285 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9286 B = APFloat::copySign(
9287 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9288 if (C.isNaN())
9289 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9290 if (D.isNaN())
9291 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9292 Recalc = true;
9293 }
9294 if (C.isInfinity() || D.isInfinity()) {
9295 C = APFloat::copySign(
9296 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9297 D = APFloat::copySign(
9298 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9299 if (A.isNaN())
9300 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9301 if (B.isNaN())
9302 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9303 Recalc = true;
9304 }
9305 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9306 AD.isInfinity() || BC.isInfinity())) {
9307 if (A.isNaN())
9308 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9309 if (B.isNaN())
9310 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9311 if (C.isNaN())
9312 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9313 if (D.isNaN())
9314 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9315 Recalc = true;
9316 }
9317 if (Recalc) {
9318 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9319 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9320 }
9321 }
9322 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009323 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009324 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009325 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009326 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9327 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009328 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009329 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9330 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9331 }
9332 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009333 case BO_Div:
9334 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009335 // This is an implementation of complex division according to the
9336 // constraints laid out in C11 Annex G. The implemantion uses the
9337 // following naming scheme:
9338 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009339 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009340 APFloat &A = LHS.getComplexFloatReal();
9341 APFloat &B = LHS.getComplexFloatImag();
9342 APFloat &C = RHS.getComplexFloatReal();
9343 APFloat &D = RHS.getComplexFloatImag();
9344 APFloat &ResR = Result.getComplexFloatReal();
9345 APFloat &ResI = Result.getComplexFloatImag();
9346 if (RHSReal) {
9347 ResR = A / C;
9348 ResI = B / C;
9349 } else {
9350 if (LHSReal) {
9351 // No real optimizations we can do here, stub out with zero.
9352 B = APFloat::getZero(A.getSemantics());
9353 }
9354 int DenomLogB = 0;
9355 APFloat MaxCD = maxnum(abs(C), abs(D));
9356 if (MaxCD.isFinite()) {
9357 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009358 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9359 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009360 }
9361 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009362 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9363 APFloat::rmNearestTiesToEven);
9364 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9365 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009366 if (ResR.isNaN() && ResI.isNaN()) {
9367 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9368 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9369 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9370 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9371 D.isFinite()) {
9372 A = APFloat::copySign(
9373 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9374 B = APFloat::copySign(
9375 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9376 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9377 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9378 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9379 C = APFloat::copySign(
9380 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9381 D = APFloat::copySign(
9382 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9383 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9384 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9385 }
9386 }
9387 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009388 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009389 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9390 return Error(E, diag::note_expr_divide_by_zero);
9391
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009392 ComplexValue LHS = Result;
9393 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9394 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9395 Result.getComplexIntReal() =
9396 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9397 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9398 Result.getComplexIntImag() =
9399 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9400 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9401 }
9402 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009403 }
9404
John McCall93d91dc2010-05-07 17:22:02 +00009405 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009406}
9407
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009408bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9409 // Get the operand value into 'Result'.
9410 if (!Visit(E->getSubExpr()))
9411 return false;
9412
9413 switch (E->getOpcode()) {
9414 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009415 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009416 case UO_Extension:
9417 return true;
9418 case UO_Plus:
9419 // The result is always just the subexpr.
9420 return true;
9421 case UO_Minus:
9422 if (Result.isComplexFloat()) {
9423 Result.getComplexFloatReal().changeSign();
9424 Result.getComplexFloatImag().changeSign();
9425 }
9426 else {
9427 Result.getComplexIntReal() = -Result.getComplexIntReal();
9428 Result.getComplexIntImag() = -Result.getComplexIntImag();
9429 }
9430 return true;
9431 case UO_Not:
9432 if (Result.isComplexFloat())
9433 Result.getComplexFloatImag().changeSign();
9434 else
9435 Result.getComplexIntImag() = -Result.getComplexIntImag();
9436 return true;
9437 }
9438}
9439
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009440bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9441 if (E->getNumInits() == 2) {
9442 if (E->getType()->isComplexType()) {
9443 Result.makeComplexFloat();
9444 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9445 return false;
9446 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9447 return false;
9448 } else {
9449 Result.makeComplexInt();
9450 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9451 return false;
9452 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9453 return false;
9454 }
9455 return true;
9456 }
9457 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9458}
9459
Anders Carlsson537969c2008-11-16 20:27:53 +00009460//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009461// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9462// implicit conversion.
9463//===----------------------------------------------------------------------===//
9464
9465namespace {
9466class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009467 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00009468 APValue &Result;
9469public:
9470 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
9471 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9472
9473 bool Success(const APValue &V, const Expr *E) {
9474 Result = V;
9475 return true;
9476 }
9477
9478 bool ZeroInitialization(const Expr *E) {
9479 ImplicitValueInitExpr VIE(
9480 E->getType()->castAs<AtomicType>()->getValueType());
9481 return Evaluate(Result, Info, &VIE);
9482 }
9483
9484 bool VisitCastExpr(const CastExpr *E) {
9485 switch (E->getCastKind()) {
9486 default:
9487 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9488 case CK_NonAtomicToAtomic:
9489 return Evaluate(Result, Info, E->getSubExpr());
9490 }
9491 }
9492};
9493} // end anonymous namespace
9494
9495static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
9496 assert(E->isRValue() && E->getType()->isAtomicType());
9497 return AtomicExprEvaluator(Info, Result).Visit(E);
9498}
9499
9500//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009501// Void expression evaluation, primarily for a cast to void on the LHS of a
9502// comma operator
9503//===----------------------------------------------------------------------===//
9504
9505namespace {
9506class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009507 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009508public:
9509 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9510
Richard Smith2e312c82012-03-03 22:46:17 +00009511 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009512
9513 bool VisitCastExpr(const CastExpr *E) {
9514 switch (E->getCastKind()) {
9515 default:
9516 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9517 case CK_ToVoid:
9518 VisitIgnoredValue(E->getSubExpr());
9519 return true;
9520 }
9521 }
Hal Finkela8443c32014-07-17 14:49:58 +00009522
9523 bool VisitCallExpr(const CallExpr *E) {
9524 switch (E->getBuiltinCallee()) {
9525 default:
9526 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9527 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009528 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009529 // The argument is not evaluated!
9530 return true;
9531 }
9532 }
Richard Smith42d3af92011-12-07 00:43:50 +00009533};
9534} // end anonymous namespace
9535
9536static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9537 assert(E->isRValue() && E->getType()->isVoidType());
9538 return VoidExprEvaluator(Info).Visit(E);
9539}
9540
9541//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009542// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009543//===----------------------------------------------------------------------===//
9544
Richard Smith2e312c82012-03-03 22:46:17 +00009545static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009546 // In C, function designators are not lvalues, but we evaluate them as if they
9547 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009548 QualType T = E->getType();
9549 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009550 LValue LV;
9551 if (!EvaluateLValue(E, LV, Info))
9552 return false;
9553 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009554 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009555 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009556 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009557 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009558 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009559 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009560 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009561 LValue LV;
9562 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009563 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009564 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009565 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009566 llvm::APFloat F(0.0);
9567 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009568 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009569 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009570 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009571 ComplexValue C;
9572 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009573 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009574 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009575 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009576 MemberPtr P;
9577 if (!EvaluateMemberPointer(E, P, Info))
9578 return false;
9579 P.moveInto(Result);
9580 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009581 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009582 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009583 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009584 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9585 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009586 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009587 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009588 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009589 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009590 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009591 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9592 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009593 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009594 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009595 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009596 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009597 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009598 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009599 if (!EvaluateVoid(E, Info))
9600 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009601 } else if (T->isAtomicType()) {
9602 if (!EvaluateAtomic(E, Result, Info))
9603 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009604 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009605 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009606 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009607 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009608 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009609 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009610 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009611
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009612 return true;
9613}
9614
Richard Smithb228a862012-02-15 02:18:13 +00009615/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9616/// cases, the in-place evaluation is essential, since later initializers for
9617/// an object can indirectly refer to subobjects which were initialized earlier.
9618static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009619 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009620 assert(!E->isValueDependent());
9621
Richard Smith7525ff62013-05-09 07:14:00 +00009622 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009623 return false;
9624
9625 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009626 // Evaluate arrays and record types in-place, so that later initializers can
9627 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00009628 if (E->getType()->isArrayType())
9629 return EvaluateArray(E, This, Result, Info);
9630 else if (E->getType()->isRecordType())
9631 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00009632 }
9633
9634 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009635 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009636}
9637
Richard Smithf57d8cb2011-12-09 22:58:01 +00009638/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9639/// lvalue-to-rvalue cast if it is an lvalue.
9640static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009641 if (E->getType().isNull())
9642 return false;
9643
Richard Smithfddd3842011-12-30 21:15:51 +00009644 if (!CheckLiteralType(Info, E))
9645 return false;
9646
Richard Smith2e312c82012-03-03 22:46:17 +00009647 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009648 return false;
9649
9650 if (E->isGLValue()) {
9651 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009652 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009653 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009654 return false;
9655 }
9656
Richard Smith2e312c82012-03-03 22:46:17 +00009657 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009658 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009659}
Richard Smith11562c52011-10-28 17:51:58 +00009660
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009661static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9662 const ASTContext &Ctx, bool &IsConst) {
9663 // Fast-path evaluations of integer literals, since we sometimes see files
9664 // containing vast quantities of these.
9665 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9666 Result.Val = APValue(APSInt(L->getValue(),
9667 L->getType()->isUnsignedIntegerType()));
9668 IsConst = true;
9669 return true;
9670 }
James Dennett0492ef02014-03-14 17:44:10 +00009671
9672 // This case should be rare, but we need to check it before we check on
9673 // the type below.
9674 if (Exp->getType().isNull()) {
9675 IsConst = false;
9676 return true;
9677 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009678
9679 // FIXME: Evaluating values of large array and record types can cause
9680 // performance problems. Only do so in C++11 for now.
9681 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9682 Exp->getType()->isRecordType()) &&
9683 !Ctx.getLangOpts().CPlusPlus11) {
9684 IsConst = false;
9685 return true;
9686 }
9687 return false;
9688}
9689
9690
Richard Smith7b553f12011-10-29 00:50:52 +00009691/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009692/// any crazy technique (that has nothing to do with language standards) that
9693/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009694/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9695/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009696bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009697 bool IsConst;
9698 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9699 return IsConst;
9700
Richard Smith6d4c6582013-11-05 22:18:15 +00009701 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009702 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009703}
9704
Jay Foad39c79802011-01-12 09:06:06 +00009705bool Expr::EvaluateAsBooleanCondition(bool &Result,
9706 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009707 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009708 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009709 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009710}
9711
Richard Smithce8eca52015-12-08 03:21:47 +00009712static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9713 Expr::SideEffectsKind SEK) {
9714 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9715 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9716}
9717
Richard Smith5fab0c92011-12-28 19:48:30 +00009718bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9719 SideEffectsKind AllowSideEffects) const {
9720 if (!getType()->isIntegralOrEnumerationType())
9721 return false;
9722
Richard Smith11562c52011-10-28 17:51:58 +00009723 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009724 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009725 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009726 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009727
Richard Smith11562c52011-10-28 17:51:58 +00009728 Result = ExprResult.Val.getInt();
9729 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009730}
9731
Richard Trieube234c32016-04-21 21:04:55 +00009732bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9733 SideEffectsKind AllowSideEffects) const {
9734 if (!getType()->isRealFloatingType())
9735 return false;
9736
9737 EvalResult ExprResult;
9738 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9739 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9740 return false;
9741
9742 Result = ExprResult.Val.getFloat();
9743 return true;
9744}
9745
Jay Foad39c79802011-01-12 09:06:06 +00009746bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009747 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009748
John McCall45d55e42010-05-07 21:00:08 +00009749 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009750 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9751 !CheckLValueConstantExpression(Info, getExprLoc(),
9752 Ctx.getLValueReferenceType(getType()), LV))
9753 return false;
9754
Richard Smith2e312c82012-03-03 22:46:17 +00009755 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009756 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009757}
9758
Richard Smithd0b4dd62011-12-19 06:19:21 +00009759bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9760 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009761 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009762 // FIXME: Evaluating initializers for large array and record types can cause
9763 // performance problems. Only do so in C++11 for now.
9764 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009765 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009766 return false;
9767
Richard Smithd0b4dd62011-12-19 06:19:21 +00009768 Expr::EvalStatus EStatus;
9769 EStatus.Diag = &Notes;
9770
Richard Smith0c6124b2015-12-03 01:36:22 +00009771 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9772 ? EvalInfo::EM_ConstantExpression
9773 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009774 InitInfo.setEvaluatingDecl(VD, Value);
9775
9776 LValue LVal;
9777 LVal.set(VD);
9778
Richard Smithfddd3842011-12-30 21:15:51 +00009779 // C++11 [basic.start.init]p2:
9780 // Variables with static storage duration or thread storage duration shall be
9781 // zero-initialized before any other initialization takes place.
9782 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009783 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009784 !VD->getType()->isReferenceType()) {
9785 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009786 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009787 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009788 return false;
9789 }
9790
Richard Smith7525ff62013-05-09 07:14:00 +00009791 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9792 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009793 EStatus.HasSideEffects)
9794 return false;
9795
9796 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9797 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009798}
9799
Richard Smith7b553f12011-10-29 00:50:52 +00009800/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9801/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009802bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009803 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009804 return EvaluateAsRValue(Result, Ctx) &&
9805 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009806}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009807
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009808APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009809 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009810 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009811 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009812 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009813 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009814 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009815 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009816
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009817 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009818}
John McCall864e3962010-05-07 05:32:02 +00009819
Richard Smithe9ff7702013-11-05 22:23:30 +00009820void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009821 bool IsConst;
9822 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009823 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009824 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009825 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9826 }
9827}
9828
Richard Smithe6c01442013-06-05 00:46:14 +00009829bool Expr::EvalResult::isGlobalLValue() const {
9830 assert(Val.isLValue());
9831 return IsGlobalLValue(Val.getLValueBase());
9832}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009833
9834
John McCall864e3962010-05-07 05:32:02 +00009835/// isIntegerConstantExpr - this recursive routine will test if an expression is
9836/// an integer constant expression.
9837
9838/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9839/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009840
9841// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009842// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9843// and a (possibly null) SourceLocation indicating the location of the problem.
9844//
John McCall864e3962010-05-07 05:32:02 +00009845// Note that to reduce code duplication, this helper does no evaluation
9846// itself; the caller checks whether the expression is evaluatable, and
9847// in the rare cases where CheckICE actually cares about the evaluated
9848// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00009849
Dan Gohman28ade552010-07-26 21:25:24 +00009850namespace {
9851
Richard Smith9e575da2012-12-28 13:25:52 +00009852enum ICEKind {
9853 /// This expression is an ICE.
9854 IK_ICE,
9855 /// This expression is not an ICE, but if it isn't evaluated, it's
9856 /// a legal subexpression for an ICE. This return value is used to handle
9857 /// the comma operator in C99 mode, and non-constant subexpressions.
9858 IK_ICEIfUnevaluated,
9859 /// This expression is not an ICE, and is not a legal subexpression for one.
9860 IK_NotICE
9861};
9862
John McCall864e3962010-05-07 05:32:02 +00009863struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009864 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009865 SourceLocation Loc;
9866
Richard Smith9e575da2012-12-28 13:25:52 +00009867 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009868};
9869
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009870}
Dan Gohman28ade552010-07-26 21:25:24 +00009871
Richard Smith9e575da2012-12-28 13:25:52 +00009872static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9873
9874static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00009875
Craig Toppera31a8822013-08-22 07:09:37 +00009876static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009877 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00009878 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00009879 !EVResult.Val.isInt())
9880 return ICEDiag(IK_NotICE, E->getLocStart());
9881
John McCall864e3962010-05-07 05:32:02 +00009882 return NoDiag();
9883}
9884
Craig Toppera31a8822013-08-22 07:09:37 +00009885static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009886 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00009887 if (!E->getType()->isIntegralOrEnumerationType())
9888 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009889
9890 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00009891#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00009892#define STMT(Node, Base) case Expr::Node##Class:
9893#define EXPR(Node, Base)
9894#include "clang/AST/StmtNodes.inc"
9895 case Expr::PredefinedExprClass:
9896 case Expr::FloatingLiteralClass:
9897 case Expr::ImaginaryLiteralClass:
9898 case Expr::StringLiteralClass:
9899 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009900 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00009901 case Expr::MemberExprClass:
9902 case Expr::CompoundAssignOperatorClass:
9903 case Expr::CompoundLiteralExprClass:
9904 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00009905 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00009906 case Expr::ArrayInitLoopExprClass:
9907 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00009908 case Expr::NoInitExprClass:
9909 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00009910 case Expr::ImplicitValueInitExprClass:
9911 case Expr::ParenListExprClass:
9912 case Expr::VAArgExprClass:
9913 case Expr::AddrLabelExprClass:
9914 case Expr::StmtExprClass:
9915 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00009916 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00009917 case Expr::CXXDynamicCastExprClass:
9918 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00009919 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00009920 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00009921 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009922 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00009923 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009924 case Expr::CXXThisExprClass:
9925 case Expr::CXXThrowExprClass:
9926 case Expr::CXXNewExprClass:
9927 case Expr::CXXDeleteExprClass:
9928 case Expr::CXXPseudoDestructorExprClass:
9929 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00009930 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00009931 case Expr::DependentScopeDeclRefExprClass:
9932 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00009933 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00009934 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00009935 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00009936 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00009937 case Expr::CXXTemporaryObjectExprClass:
9938 case Expr::CXXUnresolvedConstructExprClass:
9939 case Expr::CXXDependentScopeMemberExprClass:
9940 case Expr::UnresolvedMemberExprClass:
9941 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00009942 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009943 case Expr::ObjCArrayLiteralClass:
9944 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009945 case Expr::ObjCEncodeExprClass:
9946 case Expr::ObjCMessageExprClass:
9947 case Expr::ObjCSelectorExprClass:
9948 case Expr::ObjCProtocolExprClass:
9949 case Expr::ObjCIvarRefExprClass:
9950 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009951 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00009952 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00009953 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +00009954 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00009955 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00009956 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00009957 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00009958 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00009959 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00009960 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00009961 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00009962 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00009963 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00009964 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00009965 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00009966 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00009967 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00009968 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00009969 case Expr::CoawaitExprClass:
9970 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00009971 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00009972
Richard Smithf137f932014-01-25 20:50:08 +00009973 case Expr::InitListExprClass: {
9974 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9975 // form "T x = { a };" is equivalent to "T x = a;".
9976 // Unless we're initializing a reference, T is a scalar as it is known to be
9977 // of integral or enumeration type.
9978 if (E->isRValue())
9979 if (cast<InitListExpr>(E)->getNumInits() == 1)
9980 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9981 return ICEDiag(IK_NotICE, E->getLocStart());
9982 }
9983
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009984 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00009985 case Expr::GNUNullExprClass:
9986 // GCC considers the GNU __null value to be an integral constant expression.
9987 return NoDiag();
9988
John McCall7c454bb2011-07-15 05:09:51 +00009989 case Expr::SubstNonTypeTemplateParmExprClass:
9990 return
9991 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9992
John McCall864e3962010-05-07 05:32:02 +00009993 case Expr::ParenExprClass:
9994 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00009995 case Expr::GenericSelectionExprClass:
9996 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009997 case Expr::IntegerLiteralClass:
9998 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009999 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010000 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010001 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010002 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010003 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010004 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010005 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010006 return NoDiag();
10007 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010008 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010009 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10010 // constant expressions, but they can never be ICEs because an ICE cannot
10011 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010012 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010013 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010014 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010015 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010016 }
Richard Smith6365c912012-02-24 22:12:32 +000010017 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010018 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10019 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010020 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010021 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010022 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010023 // Parameter variables are never constants. Without this check,
10024 // getAnyInitializer() can find a default argument, which leads
10025 // to chaos.
10026 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010027 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010028
10029 // C++ 7.1.5.1p2
10030 // A variable of non-volatile const-qualified integral or enumeration
10031 // type initialized by an ICE can be used in ICEs.
10032 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010033 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010034 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010035
Richard Smithd0b4dd62011-12-19 06:19:21 +000010036 const VarDecl *VD;
10037 // Look for a declaration of this variable that has an initializer, and
10038 // check whether it is an ICE.
10039 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10040 return NoDiag();
10041 else
Richard Smith9e575da2012-12-28 13:25:52 +000010042 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010043 }
10044 }
Richard Smith9e575da2012-12-28 13:25:52 +000010045 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010046 }
John McCall864e3962010-05-07 05:32:02 +000010047 case Expr::UnaryOperatorClass: {
10048 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10049 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010050 case UO_PostInc:
10051 case UO_PostDec:
10052 case UO_PreInc:
10053 case UO_PreDec:
10054 case UO_AddrOf:
10055 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010056 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010057 // C99 6.6/3 allows increment and decrement within unevaluated
10058 // subexpressions of constant expressions, but they can never be ICEs
10059 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010060 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010061 case UO_Extension:
10062 case UO_LNot:
10063 case UO_Plus:
10064 case UO_Minus:
10065 case UO_Not:
10066 case UO_Real:
10067 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010068 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010069 }
Richard Smith9e575da2012-12-28 13:25:52 +000010070
John McCall864e3962010-05-07 05:32:02 +000010071 // OffsetOf falls through here.
10072 }
10073 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010074 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10075 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10076 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10077 // compliance: we should warn earlier for offsetof expressions with
10078 // array subscripts that aren't ICEs, and if the array subscripts
10079 // are ICEs, the value of the offsetof must be an integer constant.
10080 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010081 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010082 case Expr::UnaryExprOrTypeTraitExprClass: {
10083 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10084 if ((Exp->getKind() == UETT_SizeOf) &&
10085 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010086 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010087 return NoDiag();
10088 }
10089 case Expr::BinaryOperatorClass: {
10090 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10091 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010092 case BO_PtrMemD:
10093 case BO_PtrMemI:
10094 case BO_Assign:
10095 case BO_MulAssign:
10096 case BO_DivAssign:
10097 case BO_RemAssign:
10098 case BO_AddAssign:
10099 case BO_SubAssign:
10100 case BO_ShlAssign:
10101 case BO_ShrAssign:
10102 case BO_AndAssign:
10103 case BO_XorAssign:
10104 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000010105 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10106 // constant expressions, but they can never be ICEs because an ICE cannot
10107 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010108 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010109
John McCalle3027922010-08-25 11:45:40 +000010110 case BO_Mul:
10111 case BO_Div:
10112 case BO_Rem:
10113 case BO_Add:
10114 case BO_Sub:
10115 case BO_Shl:
10116 case BO_Shr:
10117 case BO_LT:
10118 case BO_GT:
10119 case BO_LE:
10120 case BO_GE:
10121 case BO_EQ:
10122 case BO_NE:
10123 case BO_And:
10124 case BO_Xor:
10125 case BO_Or:
10126 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010127 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10128 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010129 if (Exp->getOpcode() == BO_Div ||
10130 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010131 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010132 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010133 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010134 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010135 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010136 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010137 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010138 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010139 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010140 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010141 }
10142 }
10143 }
John McCalle3027922010-08-25 11:45:40 +000010144 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010145 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010146 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10147 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010148 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10149 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010150 } else {
10151 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010152 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010153 }
10154 }
Richard Smith9e575da2012-12-28 13:25:52 +000010155 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010156 }
John McCalle3027922010-08-25 11:45:40 +000010157 case BO_LAnd:
10158 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010159 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10160 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010161 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010162 // Rare case where the RHS has a comma "side-effect"; we need
10163 // to actually check the condition to see whether the side
10164 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010165 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010166 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010167 return RHSResult;
10168 return NoDiag();
10169 }
10170
Richard Smith9e575da2012-12-28 13:25:52 +000010171 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010172 }
10173 }
10174 }
10175 case Expr::ImplicitCastExprClass:
10176 case Expr::CStyleCastExprClass:
10177 case Expr::CXXFunctionalCastExprClass:
10178 case Expr::CXXStaticCastExprClass:
10179 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010180 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010181 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010182 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010183 if (isa<ExplicitCastExpr>(E)) {
10184 if (const FloatingLiteral *FL
10185 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10186 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10187 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10188 APSInt IgnoredVal(DestWidth, !DestSigned);
10189 bool Ignored;
10190 // If the value does not fit in the destination type, the behavior is
10191 // undefined, so we are not required to treat it as a constant
10192 // expression.
10193 if (FL->getValue().convertToInteger(IgnoredVal,
10194 llvm::APFloat::rmTowardZero,
10195 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010196 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010197 return NoDiag();
10198 }
10199 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010200 switch (cast<CastExpr>(E)->getCastKind()) {
10201 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010202 case CK_AtomicToNonAtomic:
10203 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010204 case CK_NoOp:
10205 case CK_IntegralToBoolean:
10206 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010207 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010208 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010209 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010210 }
John McCall864e3962010-05-07 05:32:02 +000010211 }
John McCallc07a0c72011-02-17 10:25:35 +000010212 case Expr::BinaryConditionalOperatorClass: {
10213 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10214 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010215 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010216 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010217 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10218 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10219 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010220 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010221 return FalseResult;
10222 }
John McCall864e3962010-05-07 05:32:02 +000010223 case Expr::ConditionalOperatorClass: {
10224 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10225 // If the condition (ignoring parens) is a __builtin_constant_p call,
10226 // then only the true side is actually considered in an integer constant
10227 // expression, and it is fully evaluated. This is an important GNU
10228 // extension. See GCC PR38377 for discussion.
10229 if (const CallExpr *CallCE
10230 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010231 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010232 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010233 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010234 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010235 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010236
Richard Smithf57d8cb2011-12-09 22:58:01 +000010237 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10238 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010239
Richard Smith9e575da2012-12-28 13:25:52 +000010240 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010241 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010242 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010243 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010244 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010245 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010246 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010247 return NoDiag();
10248 // Rare case where the diagnostics depend on which side is evaluated
10249 // Note that if we get here, CondResult is 0, and at least one of
10250 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010251 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010252 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010253 return TrueResult;
10254 }
10255 case Expr::CXXDefaultArgExprClass:
10256 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010257 case Expr::CXXDefaultInitExprClass:
10258 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010259 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010260 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010261 }
10262 }
10263
David Blaikiee4d798f2012-01-20 21:50:17 +000010264 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010265}
10266
Richard Smithf57d8cb2011-12-09 22:58:01 +000010267/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010268static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010269 const Expr *E,
10270 llvm::APSInt *Value,
10271 SourceLocation *Loc) {
10272 if (!E->getType()->isIntegralOrEnumerationType()) {
10273 if (Loc) *Loc = E->getExprLoc();
10274 return false;
10275 }
10276
Richard Smith66e05fe2012-01-18 05:21:49 +000010277 APValue Result;
10278 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010279 return false;
10280
Richard Smith98710fc2014-11-13 23:03:19 +000010281 if (!Result.isInt()) {
10282 if (Loc) *Loc = E->getExprLoc();
10283 return false;
10284 }
10285
Richard Smith66e05fe2012-01-18 05:21:49 +000010286 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010287 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010288}
10289
Craig Toppera31a8822013-08-22 07:09:37 +000010290bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10291 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010292 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010293 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010294
Richard Smith9e575da2012-12-28 13:25:52 +000010295 ICEDiag D = CheckICE(this, Ctx);
10296 if (D.Kind != IK_ICE) {
10297 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010298 return false;
10299 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010300 return true;
10301}
10302
Craig Toppera31a8822013-08-22 07:09:37 +000010303bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010304 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010305 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010306 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10307
10308 if (!isIntegerConstantExpr(Ctx, Loc))
10309 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010310 // The only possible side-effects here are due to UB discovered in the
10311 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10312 // required to treat the expression as an ICE, so we produce the folded
10313 // value.
10314 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010315 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010316 return true;
10317}
Richard Smith66e05fe2012-01-18 05:21:49 +000010318
Craig Toppera31a8822013-08-22 07:09:37 +000010319bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010320 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010321}
10322
Craig Toppera31a8822013-08-22 07:09:37 +000010323bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010324 SourceLocation *Loc) const {
10325 // We support this checking in C++98 mode in order to diagnose compatibility
10326 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010327 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010328
Richard Smith98a0a492012-02-14 21:38:30 +000010329 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010330 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010331 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010332 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010333 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010334
10335 APValue Scratch;
10336 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10337
10338 if (!Diags.empty()) {
10339 IsConstExpr = false;
10340 if (Loc) *Loc = Diags[0].first;
10341 } else if (!IsConstExpr) {
10342 // FIXME: This shouldn't happen.
10343 if (Loc) *Loc = getExprLoc();
10344 }
10345
10346 return IsConstExpr;
10347}
Richard Smith253c2a32012-01-27 01:14:48 +000010348
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010349bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10350 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +000010351 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010352 Expr::EvalStatus Status;
10353 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10354
10355 ArgVector ArgValues(Args.size());
10356 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10357 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010358 if ((*I)->isValueDependent() ||
10359 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010360 // If evaluation fails, throw away the argument entirely.
10361 ArgValues[I - Args.begin()] = APValue();
10362 if (Info.EvalStatus.HasSideEffects)
10363 return false;
10364 }
10365
10366 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +000010367 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010368 ArgValues.data());
10369 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10370}
10371
Richard Smith253c2a32012-01-27 01:14:48 +000010372bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010373 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010374 PartialDiagnosticAt> &Diags) {
10375 // FIXME: It would be useful to check constexpr function templates, but at the
10376 // moment the constant expression evaluator cannot cope with the non-rigorous
10377 // ASTs which we build for dependent expressions.
10378 if (FD->isDependentContext())
10379 return true;
10380
10381 Expr::EvalStatus Status;
10382 Status.Diag = &Diags;
10383
Richard Smith6d4c6582013-11-05 22:18:15 +000010384 EvalInfo Info(FD->getASTContext(), Status,
10385 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010386
10387 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010388 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010389
Richard Smith7525ff62013-05-09 07:14:00 +000010390 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010391 // is a temporary being used as the 'this' pointer.
10392 LValue This;
10393 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010394 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010395
Richard Smith253c2a32012-01-27 01:14:48 +000010396 ArrayRef<const Expr*> Args;
10397
Richard Smith2e312c82012-03-03 22:46:17 +000010398 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010399 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10400 // Evaluate the call as a constant initializer, to allow the construction
10401 // of objects of non-literal types.
10402 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010403 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10404 } else {
10405 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010406 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010407 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010408 }
Richard Smith253c2a32012-01-27 01:14:48 +000010409
10410 return Diags.empty();
10411}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010412
10413bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10414 const FunctionDecl *FD,
10415 SmallVectorImpl<
10416 PartialDiagnosticAt> &Diags) {
10417 Expr::EvalStatus Status;
10418 Status.Diag = &Diags;
10419
10420 EvalInfo Info(FD->getASTContext(), Status,
10421 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10422
10423 // Fabricate a call stack frame to give the arguments a plausible cover story.
10424 ArrayRef<const Expr*> Args;
10425 ArgVector ArgValues(0);
10426 bool Success = EvaluateArgs(Args, ArgValues, Info);
10427 (void)Success;
10428 assert(Success &&
10429 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010430 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010431
10432 APValue ResultScratch;
10433 Evaluate(ResultScratch, Info, E);
10434 return Diags.empty();
10435}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010436
10437bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10438 unsigned Type) const {
10439 if (!getType()->isPointerType())
10440 return false;
10441
10442 Expr::EvalStatus Status;
10443 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVa7470272016-12-20 01:05:42 +000010444 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010445}