blob: 3af64bc09a0e5d6bedbc5bfc6746d95154274fdc [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000039#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000040#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000041#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000042#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000043#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000044#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000045#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000046#include "clang/Basic/TargetInfo.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
Richard Smith84401042013-06-03 05:03:02 +000066
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000079 // for it directly. Otherwise use the type after adjustment.
80 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000081 return Inner->getType();
82 }
83
84 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000085 }
86
Richard Smithd62306a2011-11-10 06:34:14 +000087 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000088 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000089 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000090 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000091 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000093 return Value;
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000098 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000099 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000110 }
111
George Burgess IVe3763372016-12-22 02:50:20 +0000112 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
113 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
114 const FunctionDecl *Callee = CE->getDirectCallee();
115 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
116 }
117
118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119 /// This will look through a single cast.
120 ///
121 /// Returns null if we couldn't unwrap a function with alloc_size.
122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123 if (!E->getType()->isPointerType())
124 return nullptr;
125
126 E = E->IgnoreParens();
127 // If we're doing a variable assignment from e.g. malloc(N), there will
128 // probably be a cast of some kind. Ignore it.
129 if (const auto *Cast = dyn_cast<CastExpr>(E))
130 E = Cast->getSubExpr()->IgnoreParens();
131
132 if (const auto *CE = dyn_cast<CallExpr>(E))
133 return getAllocSizeAttr(CE) ? CE : nullptr;
134 return nullptr;
135 }
136
137 /// Determines whether or not the given Base contains a call to a function
138 /// with the alloc_size attribute.
139 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
140 const auto *E = Base.dyn_cast<const Expr *>();
141 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
142 }
143
Richard Smith2cd56042017-08-29 01:52:13 +0000144 /// The bound to claim that an array of unknown bound has.
145 /// The value in MostDerivedArraySize is undefined in this case. So, set it
146 /// to an arbitrary value that's likely to loudly break things if it's used.
147 static const uint64_t AssumedSizeForUnsizedArray =
148 std::numeric_limits<uint64_t>::max() / 2;
149
George Burgess IVe3763372016-12-22 02:50:20 +0000150 /// Determines if an LValue with the given LValueBase will have an unsized
151 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000152 /// Find the path length and type of the most-derived subobject in the given
153 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000154 static unsigned
155 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
156 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith2cd56042017-08-29 01:52:13 +0000157 uint64_t &ArraySize, QualType &Type, bool &IsArray,
158 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000159 // This only accepts LValueBases from APValues, and APValues don't support
160 // arrays that lack size info.
161 assert(!isBaseAnAllocSizeCall(Base) &&
162 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000163 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000164 Type = getType(Base);
165
Richard Smith80815602011-11-07 05:07:52 +0000166 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000167 if (Type->isArrayType()) {
Richard Smith2cd56042017-08-29 01:52:13 +0000168 const ArrayType *AT = Ctx.getAsArrayType(Type);
169 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000170 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000171 IsArray = true;
Richard Smith2cd56042017-08-29 01:52:13 +0000172
173 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
174 ArraySize = CAT->getSize().getZExtValue();
175 } else {
176 assert(I == 0 && "unexpected unsized array designator");
177 FirstEntryIsUnsizedArray = true;
178 ArraySize = AssumedSizeForUnsizedArray;
179 }
Richard Smith66c96992012-02-18 22:04:06 +0000180 } else if (Type->isAnyComplexType()) {
181 const ComplexType *CT = Type->castAs<ComplexType>();
182 Type = CT->getElementType();
183 ArraySize = 2;
184 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000185 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000186 } else if (const FieldDecl *FD = getAsField(Path[I])) {
187 Type = FD->getType();
188 ArraySize = 0;
189 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000190 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000191 } else {
Richard Smith80815602011-11-07 05:07:52 +0000192 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000193 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000194 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000195 }
Richard Smith80815602011-11-07 05:07:52 +0000196 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000197 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000198 }
199
Richard Smitha8105bc2012-01-06 16:39:00 +0000200 // The order of this enum is important for diagnostics.
201 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000202 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000203 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000204 };
205
Richard Smith96e0c102011-11-04 02:25:55 +0000206 /// A path from a glvalue to a subobject of that glvalue.
207 struct SubobjectDesignator {
208 /// True if the subobject was named in a manner not supported by C++11. Such
209 /// lvalues can still be folded, but they are not core constant expressions
210 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000211 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000212
Richard Smitha8105bc2012-01-06 16:39:00 +0000213 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000214 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000215
Daniel Jasperffdee092017-05-02 19:21:42 +0000216 /// Indicator of whether the first entry is an unsized array.
217 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000218
George Burgess IVa51c4072015-10-16 01:49:01 +0000219 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000220 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000221
Richard Smitha8105bc2012-01-06 16:39:00 +0000222 /// The length of the path to the most-derived object of which this is a
223 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000224 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000225
George Burgess IVa51c4072015-10-16 01:49:01 +0000226 /// The size of the array of which the most-derived object is an element.
227 /// This will always be 0 if the most-derived object is not an array
228 /// element. 0 is not an indicator of whether or not the most-derived object
229 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000230 ///
231 /// If the current array is an unsized array, the value of this is
232 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000233 uint64_t MostDerivedArraySize;
234
235 /// The type of the most derived object referred to by this address.
236 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000237
Richard Smith80815602011-11-07 05:07:52 +0000238 typedef APValue::LValuePathEntry PathEntry;
239
Richard Smith96e0c102011-11-04 02:25:55 +0000240 /// The entries on the path from the glvalue to the designated subobject.
241 SmallVector<PathEntry, 8> Entries;
242
Richard Smitha8105bc2012-01-06 16:39:00 +0000243 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000244
Richard Smitha8105bc2012-01-06 16:39:00 +0000245 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000246 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000247 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000248 MostDerivedPathLength(0), MostDerivedArraySize(0),
249 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000250
251 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000252 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000253 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000254 MostDerivedPathLength(0), MostDerivedArraySize(0) {
255 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000256 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000257 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000258 ArrayRef<PathEntry> VEntries = V.getLValuePath();
259 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000260 if (V.getLValueBase()) {
261 bool IsArray = false;
Richard Smith2cd56042017-08-29 01:52:13 +0000262 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000263 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000264 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith2cd56042017-08-29 01:52:13 +0000265 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000266 MostDerivedIsArrayElement = IsArray;
Richard Smith2cd56042017-08-29 01:52:13 +0000267 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000268 }
Richard Smith80815602011-11-07 05:07:52 +0000269 }
270 }
271
Richard Smith96e0c102011-11-04 02:25:55 +0000272 void setInvalid() {
273 Invalid = true;
274 Entries.clear();
275 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000276
George Burgess IVe3763372016-12-22 02:50:20 +0000277 /// Determine whether the most derived subobject is an array without a
278 /// known bound.
279 bool isMostDerivedAnUnsizedArray() const {
280 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000281 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000282 }
283
284 /// Determine what the most derived array's size is. Results in an assertion
285 /// failure if the most derived array lacks a size.
286 uint64_t getMostDerivedArraySize() const {
287 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
288 return MostDerivedArraySize;
289 }
290
Richard Smitha8105bc2012-01-06 16:39:00 +0000291 /// Determine whether this is a one-past-the-end pointer.
292 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000293 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000294 if (IsOnePastTheEnd)
295 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000296 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000297 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
298 return true;
299 return false;
300 }
301
302 /// Check that this refers to a valid subobject.
303 bool isValidSubobject() const {
304 if (Invalid)
305 return false;
306 return !isOnePastTheEnd();
307 }
308 /// Check that this refers to a valid subobject, and if not, produce a
309 /// relevant diagnostic and set the designator as invalid.
310 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
311
312 /// Update this designator to refer to the first element within this array.
313 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000314 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000315 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000316 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000317
318 // This is a most-derived object.
319 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000320 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000321 MostDerivedArraySize = CAT->getSize().getZExtValue();
322 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000323 }
George Burgess IVe3763372016-12-22 02:50:20 +0000324 /// Update this designator to refer to the first element within the array of
325 /// elements of type T. This is an array of unknown size.
326 void addUnsizedArrayUnchecked(QualType ElemTy) {
327 PathEntry Entry;
328 Entry.ArrayIndex = 0;
329 Entries.push_back(Entry);
330
331 MostDerivedType = ElemTy;
332 MostDerivedIsArrayElement = true;
333 // The value in MostDerivedArraySize is undefined in this case. So, set it
334 // to an arbitrary value that's likely to loudly break things if it's
335 // used.
Richard Smith2cd56042017-08-29 01:52:13 +0000336 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000337 MostDerivedPathLength = Entries.size();
338 }
Richard Smith96e0c102011-11-04 02:25:55 +0000339 /// Update this designator to refer to the given base or member of this
340 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000341 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000342 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000343 APValue::BaseOrMemberType Value(D, Virtual);
344 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000345 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000346
347 // If this isn't a base class, it's a new most-derived object.
348 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
349 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000350 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000351 MostDerivedArraySize = 0;
352 MostDerivedPathLength = Entries.size();
353 }
Richard Smith96e0c102011-11-04 02:25:55 +0000354 }
Richard Smith66c96992012-02-18 22:04:06 +0000355 /// Update this designator to refer to the given complex component.
356 void addComplexUnchecked(QualType EltTy, bool Imag) {
357 PathEntry Entry;
358 Entry.ArrayIndex = Imag;
359 Entries.push_back(Entry);
360
361 // This is technically a most-derived object, though in practice this
362 // is unlikely to matter.
363 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000364 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000365 MostDerivedArraySize = 2;
366 MostDerivedPathLength = Entries.size();
367 }
Richard Smith2cd56042017-08-29 01:52:13 +0000368 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000369 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
370 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000371 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000372 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
373 if (Invalid || !N) return;
374 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
375 if (isMostDerivedAnUnsizedArray()) {
Richard Smith2cd56042017-08-29 01:52:13 +0000376 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000377 // Can't verify -- trust that the user is doing the right thing (or if
378 // not, trust that the caller will catch the bad behavior).
379 // FIXME: Should we reject if this overflows, at least?
380 Entries.back().ArrayIndex += TruncatedN;
381 return;
382 }
383
384 // [expr.add]p4: For the purposes of these operators, a pointer to a
385 // nonarray object behaves the same as a pointer to the first element of
386 // an array of length one with the type of the object as its element type.
387 bool IsArray = MostDerivedPathLength == Entries.size() &&
388 MostDerivedIsArrayElement;
389 uint64_t ArrayIndex =
390 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
391 uint64_t ArraySize =
392 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
393
394 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
395 // Calculate the actual index in a wide enough type, so we can include
396 // it in the note.
397 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
398 (llvm::APInt&)N += ArrayIndex;
399 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
400 diagnosePointerArithmetic(Info, E, N);
401 setInvalid();
402 return;
403 }
404
405 ArrayIndex += TruncatedN;
406 assert(ArrayIndex <= ArraySize &&
407 "bounds check succeeded for out-of-bounds index");
408
409 if (IsArray)
410 Entries.back().ArrayIndex = ArrayIndex;
411 else
412 IsOnePastTheEnd = (ArrayIndex != 0);
413 }
Richard Smith96e0c102011-11-04 02:25:55 +0000414 };
415
Richard Smith254a73d2011-10-28 22:34:42 +0000416 /// A stack frame in the constexpr call stack.
417 struct CallStackFrame {
418 EvalInfo &Info;
419
420 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000421 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000422
Richard Smithf6f003a2011-12-16 19:06:07 +0000423 /// Callee - The function which was called.
424 const FunctionDecl *Callee;
425
Richard Smithd62306a2011-11-10 06:34:14 +0000426 /// This - The binding for the this pointer in this call, if any.
427 const LValue *This;
428
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000429 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000430 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000431 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000432
Eli Friedman4830ec82012-06-25 21:21:08 +0000433 // Note that we intentionally use std::map here so that references to
434 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000435 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000436 typedef MapTy::const_iterator temp_iterator;
437 /// Temporaries - Temporary lvalues materialized within this stack frame.
438 MapTy Temporaries;
439
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000440 /// CallLoc - The location of the call expression for this call.
441 SourceLocation CallLoc;
442
443 /// Index - The call index of this call.
444 unsigned Index;
445
Faisal Vali051e3a22017-02-16 04:12:21 +0000446 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
447 // on the overall stack usage of deeply-recursing constexpr evaluataions.
448 // (We should cache this map rather than recomputing it repeatedly.)
449 // But let's try this and see how it goes; we can look into caching the map
450 // as a later change.
451
452 /// LambdaCaptureFields - Mapping from captured variables/this to
453 /// corresponding data members in the closure class.
454 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
455 FieldDecl *LambdaThisCaptureField;
456
Richard Smithf6f003a2011-12-16 19:06:07 +0000457 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
458 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000459 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000460 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000461
462 APValue *getTemporary(const void *Key) {
463 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000464 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000465 }
466 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000467 };
468
Richard Smith852c9db2013-04-20 22:23:05 +0000469 /// Temporarily override 'this'.
470 class ThisOverrideRAII {
471 public:
472 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
473 : Frame(Frame), OldThis(Frame.This) {
474 if (Enable)
475 Frame.This = NewThis;
476 }
477 ~ThisOverrideRAII() {
478 Frame.This = OldThis;
479 }
480 private:
481 CallStackFrame &Frame;
482 const LValue *OldThis;
483 };
484
Richard Smith92b1ce02011-12-12 09:28:41 +0000485 /// A partial diagnostic which we might know in advance that we are not going
486 /// to emit.
487 class OptionalDiagnostic {
488 PartialDiagnostic *Diag;
489
490 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000491 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
492 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000493
494 template<typename T>
495 OptionalDiagnostic &operator<<(const T &v) {
496 if (Diag)
497 *Diag << v;
498 return *this;
499 }
Richard Smithfe800032012-01-31 04:08:20 +0000500
501 OptionalDiagnostic &operator<<(const APSInt &I) {
502 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000503 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000504 I.toString(Buffer);
505 *Diag << StringRef(Buffer.data(), Buffer.size());
506 }
507 return *this;
508 }
509
510 OptionalDiagnostic &operator<<(const APFloat &F) {
511 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000512 // FIXME: Force the precision of the source value down so we don't
513 // print digits which are usually useless (we don't really care here if
514 // we truncate a digit by accident in edge cases). Ideally,
Daniel Jasperffdee092017-05-02 19:21:42 +0000515 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000516 // representation which rounds to the correct value, but it's a bit
517 // tricky to implement.
518 unsigned precision =
519 llvm::APFloat::semanticsPrecision(F.getSemantics());
520 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000521 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000522 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000523 *Diag << StringRef(Buffer.data(), Buffer.size());
524 }
525 return *this;
526 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000527 };
528
Richard Smith08d6a2c2013-07-24 07:11:57 +0000529 /// A cleanup, and a flag indicating whether it is lifetime-extended.
530 class Cleanup {
531 llvm::PointerIntPair<APValue*, 1, bool> Value;
532
533 public:
534 Cleanup(APValue *Val, bool IsLifetimeExtended)
535 : Value(Val, IsLifetimeExtended) {}
536
537 bool isLifetimeExtended() const { return Value.getInt(); }
538 void endLifetime() {
539 *Value.getPointer() = APValue();
540 }
541 };
542
Richard Smithb228a862012-02-15 02:18:13 +0000543 /// EvalInfo - This is a private struct used by the evaluator to capture
544 /// information about a subexpression as it is folded. It retains information
545 /// about the AST context, but also maintains information about the folded
546 /// expression.
547 ///
548 /// If an expression could be evaluated, it is still possible it is not a C
549 /// "integer constant expression" or constant expression. If not, this struct
550 /// captures information about how and why not.
551 ///
552 /// One bit of information passed *into* the request for constant folding
553 /// indicates whether the subexpression is "evaluated" or not according to C
554 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
555 /// evaluate the expression regardless of what the RHS is, but C only allows
556 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000557 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000558 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000559
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000560 /// EvalStatus - Contains information about the evaluation.
561 Expr::EvalStatus &EvalStatus;
562
563 /// CurrentCall - The top of the constexpr call stack.
564 CallStackFrame *CurrentCall;
565
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000566 /// CallStackDepth - The number of calls in the call stack right now.
567 unsigned CallStackDepth;
568
Richard Smithb228a862012-02-15 02:18:13 +0000569 /// NextCallIndex - The next call index to assign.
570 unsigned NextCallIndex;
571
Richard Smitha3d3bd22013-05-08 02:12:03 +0000572 /// StepsLeft - The remaining number of evaluation steps we're permitted
573 /// to perform. This is essentially a limit for the number of statements
574 /// we will evaluate.
575 unsigned StepsLeft;
576
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000577 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000578 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000579 CallStackFrame BottomFrame;
580
Richard Smith08d6a2c2013-07-24 07:11:57 +0000581 /// A stack of values whose lifetimes end at the end of some surrounding
582 /// evaluation frame.
583 llvm::SmallVector<Cleanup, 16> CleanupStack;
584
Richard Smithd62306a2011-11-10 06:34:14 +0000585 /// EvaluatingDecl - This is the declaration whose initializer is being
586 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000587 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000588
589 /// EvaluatingDeclValue - This is the value being constructed for the
590 /// declaration whose initializer is being evaluated, if any.
591 APValue *EvaluatingDeclValue;
592
Richard Smith410306b2016-12-12 02:53:20 +0000593 /// The current array initialization index, if we're performing array
594 /// initialization.
595 uint64_t ArrayInitIndex = -1;
596
Richard Smith357362d2011-12-13 06:39:58 +0000597 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
598 /// notes attached to it will also be stored, otherwise they will not be.
599 bool HasActiveDiagnostic;
600
Richard Smith0c6124b2015-12-03 01:36:22 +0000601 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
602 /// fold (not just why it's not strictly a constant expression)?
603 bool HasFoldFailureDiagnostic;
604
George Burgess IV8c892b52016-05-25 22:31:54 +0000605 /// \brief Whether or not we're currently speculatively evaluating.
606 bool IsSpeculativelyEvaluating;
607
Richard Smith6d4c6582013-11-05 22:18:15 +0000608 enum EvaluationMode {
609 /// Evaluate as a constant expression. Stop if we find that the expression
610 /// is not a constant expression.
611 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000612
Richard Smith6d4c6582013-11-05 22:18:15 +0000613 /// Evaluate as a potential constant expression. Keep going if we hit a
614 /// construct that we can't evaluate yet (because we don't yet know the
615 /// value of something) but stop if we hit something that could never be
616 /// a constant expression.
617 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000618
Richard Smith6d4c6582013-11-05 22:18:15 +0000619 /// Fold the expression to a constant. Stop if we hit a side-effect that
620 /// we can't model.
621 EM_ConstantFold,
622
623 /// Evaluate the expression looking for integer overflow and similar
624 /// issues. Don't worry about side-effects, and try to visit all
625 /// subexpressions.
626 EM_EvaluateForOverflow,
627
628 /// Evaluate in any way we know how. Don't worry about side-effects that
629 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000630 EM_IgnoreSideEffects,
631
632 /// Evaluate as a constant expression. Stop if we find that the expression
633 /// is not a constant expression. Some expressions can be retried in the
634 /// optimizer if we don't constant fold them here, but in an unevaluated
635 /// context we try to fold them immediately since the optimizer never
636 /// gets a chance to look at it.
637 EM_ConstantExpressionUnevaluated,
638
639 /// Evaluate as a potential constant expression. Keep going if we hit a
640 /// construct that we can't evaluate yet (because we don't yet know the
641 /// value of something) but stop if we hit something that could never be
642 /// a constant expression. Some expressions can be retried in the
643 /// optimizer if we don't constant fold them here, but in an unevaluated
644 /// context we try to fold them immediately since the optimizer never
645 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000646 EM_PotentialConstantExpressionUnevaluated,
647
George Burgess IVf9013bf2017-02-10 22:52:29 +0000648 /// Evaluate as a constant expression. In certain scenarios, if:
649 /// - we find a MemberExpr with a base that can't be evaluated, or
650 /// - we find a variable initialized with a call to a function that has
651 /// the alloc_size attribute on it
652 /// then we may consider evaluation to have succeeded.
653 ///
George Burgess IVe3763372016-12-22 02:50:20 +0000654 /// In either case, the LValue returned shall have an invalid base; in the
655 /// former, the base will be the invalid MemberExpr, in the latter, the
656 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
657 /// said CallExpr.
658 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000659 } EvalMode;
660
661 /// Are we checking whether the expression is a potential constant
662 /// expression?
663 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000664 return EvalMode == EM_PotentialConstantExpression ||
665 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000666 }
667
668 /// Are we checking an expression for overflow?
669 // FIXME: We should check for any kind of undefined or suspicious behavior
670 // in such constructs, not just overflow.
671 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
672
673 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000674 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000675 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000676 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000677 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
678 EvaluatingDecl((const ValueDecl *)nullptr),
679 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000680 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
681 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000682
Richard Smith7525ff62013-05-09 07:14:00 +0000683 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
684 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000685 EvaluatingDeclValue = &Value;
686 }
687
David Blaikiebbafb8a2012-03-11 07:00:24 +0000688 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000689
Richard Smith357362d2011-12-13 06:39:58 +0000690 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000691 // Don't perform any constexpr calls (other than the call we're checking)
692 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000693 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000694 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000695 if (NextCallIndex == 0) {
696 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000697 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000698 return false;
699 }
Richard Smith357362d2011-12-13 06:39:58 +0000700 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
701 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000702 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000703 << getLangOpts().ConstexprCallDepth;
704 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000705 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000706
Richard Smithb228a862012-02-15 02:18:13 +0000707 CallStackFrame *getCallFrame(unsigned CallIndex) {
708 assert(CallIndex && "no call index in getCallFrame");
709 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
710 // be null in this loop.
711 CallStackFrame *Frame = CurrentCall;
712 while (Frame->Index > CallIndex)
713 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000714 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000715 }
716
Richard Smitha3d3bd22013-05-08 02:12:03 +0000717 bool nextStep(const Stmt *S) {
718 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000719 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000720 return false;
721 }
722 --StepsLeft;
723 return true;
724 }
725
Richard Smith357362d2011-12-13 06:39:58 +0000726 private:
727 /// Add a diagnostic to the diagnostics list.
728 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
729 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
730 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
731 return EvalStatus.Diag->back().second;
732 }
733
Richard Smithf6f003a2011-12-16 19:06:07 +0000734 /// Add notes containing a call stack to the current point of evaluation.
735 void addCallStack(unsigned Limit);
736
Faisal Valie690b7a2016-07-02 22:34:24 +0000737 private:
738 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
739 unsigned ExtraNotes, bool IsCCEDiag) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000740
Richard Smith92b1ce02011-12-12 09:28:41 +0000741 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000742 // If we have a prior diagnostic, it will be noting that the expression
743 // isn't a constant expression. This diagnostic is more important,
744 // unless we require this evaluation to produce a constant expression.
745 //
746 // FIXME: We might want to show both diagnostics to the user in
747 // EM_ConstantFold mode.
748 if (!EvalStatus.Diag->empty()) {
749 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000750 case EM_ConstantFold:
751 case EM_IgnoreSideEffects:
752 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000753 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000754 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000755 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000756 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000757 case EM_ConstantExpression:
758 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000759 case EM_ConstantExpressionUnevaluated:
760 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000761 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000762 HasActiveDiagnostic = false;
763 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000764 }
765 }
766
Richard Smithf6f003a2011-12-16 19:06:07 +0000767 unsigned CallStackNotes = CallStackDepth - 1;
768 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
769 if (Limit)
770 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000771 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000772 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000773
Richard Smith357362d2011-12-13 06:39:58 +0000774 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000775 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000776 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000777 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
778 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000779 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000780 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000781 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000782 }
Richard Smith357362d2011-12-13 06:39:58 +0000783 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000784 return OptionalDiagnostic();
785 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000786 public:
787 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
788 OptionalDiagnostic
789 FFDiag(SourceLocation Loc,
790 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
791 unsigned ExtraNotes = 0) {
792 return Diag(Loc, DiagId, ExtraNotes, false);
793 }
Daniel Jasperffdee092017-05-02 19:21:42 +0000794
Faisal Valie690b7a2016-07-02 22:34:24 +0000795 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000796 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000797 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000798 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000799 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000800 HasActiveDiagnostic = false;
801 return OptionalDiagnostic();
802 }
803
Richard Smith92b1ce02011-12-12 09:28:41 +0000804 /// Diagnose that the evaluation does not produce a C++11 core constant
805 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000806 ///
807 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
808 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000809 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000810 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000811 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000812 // Don't override a previous diagnostic. Don't bother collecting
813 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000814 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000815 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000816 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000817 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000818 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000819 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000820 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
821 = diag::note_invalid_subexpr_in_const_expr,
822 unsigned ExtraNotes = 0) {
823 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
824 }
Richard Smith357362d2011-12-13 06:39:58 +0000825 /// Add a note to a prior diagnostic.
826 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
827 if (!HasActiveDiagnostic)
828 return OptionalDiagnostic();
829 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000830 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000831
832 /// Add a stack of notes to a prior diagnostic.
833 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
834 if (HasActiveDiagnostic) {
835 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
836 Diags.begin(), Diags.end());
837 }
838 }
Richard Smith253c2a32012-01-27 01:14:48 +0000839
Richard Smith6d4c6582013-11-05 22:18:15 +0000840 /// Should we continue evaluation after encountering a side-effect that we
841 /// couldn't model?
842 bool keepEvaluatingAfterSideEffect() {
843 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000844 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000845 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000846 case EM_EvaluateForOverflow:
847 case EM_IgnoreSideEffects:
848 return true;
849
Richard Smith6d4c6582013-11-05 22:18:15 +0000850 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000851 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000852 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000853 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000854 return false;
855 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000856 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000857 }
858
859 /// Note that we have had a side-effect, and determine whether we should
860 /// keep evaluating.
861 bool noteSideEffect() {
862 EvalStatus.HasSideEffects = true;
863 return keepEvaluatingAfterSideEffect();
864 }
865
Richard Smithce8eca52015-12-08 03:21:47 +0000866 /// Should we continue evaluation after encountering undefined behavior?
867 bool keepEvaluatingAfterUndefinedBehavior() {
868 switch (EvalMode) {
869 case EM_EvaluateForOverflow:
870 case EM_IgnoreSideEffects:
871 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000872 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000873 return true;
874
875 case EM_PotentialConstantExpression:
876 case EM_PotentialConstantExpressionUnevaluated:
877 case EM_ConstantExpression:
878 case EM_ConstantExpressionUnevaluated:
879 return false;
880 }
881 llvm_unreachable("Missed EvalMode case");
882 }
883
884 /// Note that we hit something that was technically undefined behavior, but
885 /// that we can evaluate past it (such as signed overflow or floating-point
886 /// division by zero.)
887 bool noteUndefinedBehavior() {
888 EvalStatus.HasUndefinedBehavior = true;
889 return keepEvaluatingAfterUndefinedBehavior();
890 }
891
Richard Smith253c2a32012-01-27 01:14:48 +0000892 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000893 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000894 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000895 if (!StepsLeft)
896 return false;
897
898 switch (EvalMode) {
899 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000900 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000901 case EM_EvaluateForOverflow:
902 return true;
903
904 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000905 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000906 case EM_ConstantFold:
907 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000908 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000909 return false;
910 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000911 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000912 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000913
George Burgess IV8c892b52016-05-25 22:31:54 +0000914 /// Notes that we failed to evaluate an expression that other expressions
915 /// directly depend on, and determine if we should keep evaluating. This
916 /// should only be called if we actually intend to keep evaluating.
917 ///
918 /// Call noteSideEffect() instead if we may be able to ignore the value that
919 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
920 ///
921 /// (Foo(), 1) // use noteSideEffect
922 /// (Foo() || true) // use noteSideEffect
923 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000924 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000925 // Failure when evaluating some expression often means there is some
926 // subexpression whose evaluation was skipped. Therefore, (because we
927 // don't track whether we skipped an expression when unwinding after an
928 // evaluation failure) every evaluation failure that bubbles up from a
929 // subexpression implies that a side-effect has potentially happened. We
930 // skip setting the HasSideEffects flag to true until we decide to
931 // continue evaluating after that point, which happens here.
932 bool KeepGoing = keepEvaluatingAfterFailure();
933 EvalStatus.HasSideEffects |= KeepGoing;
934 return KeepGoing;
935 }
936
Richard Smith410306b2016-12-12 02:53:20 +0000937 class ArrayInitLoopIndex {
938 EvalInfo &Info;
939 uint64_t OuterIndex;
940
941 public:
942 ArrayInitLoopIndex(EvalInfo &Info)
943 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
944 Info.ArrayInitIndex = 0;
945 }
946 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
947
948 operator uint64_t&() { return Info.ArrayInitIndex; }
949 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000950 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000951
952 /// Object used to treat all foldable expressions as constant expressions.
953 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000954 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000955 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000956 bool HadNoPriorDiags;
957 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000958
Richard Smith6d4c6582013-11-05 22:18:15 +0000959 explicit FoldConstant(EvalInfo &Info, bool Enabled)
960 : Info(Info),
961 Enabled(Enabled),
962 HadNoPriorDiags(Info.EvalStatus.Diag &&
963 Info.EvalStatus.Diag->empty() &&
964 !Info.EvalStatus.HasSideEffects),
965 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000966 if (Enabled &&
967 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
968 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000969 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000970 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000971 void keepDiagnostics() { Enabled = false; }
972 ~FoldConstant() {
973 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000974 !Info.EvalStatus.HasSideEffects)
975 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000976 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000977 }
978 };
Richard Smith17100ba2012-02-16 02:46:34 +0000979
George Burgess IV3a03fab2015-09-04 21:28:13 +0000980 /// RAII object used to treat the current evaluation as the correct pointer
981 /// offset fold for the current EvalMode
982 struct FoldOffsetRAII {
983 EvalInfo &Info;
984 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +0000985 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +0000986 : Info(Info), OldMode(Info.EvalMode) {
987 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +0000988 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000989 }
990
991 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
992 };
993
George Burgess IV8c892b52016-05-25 22:31:54 +0000994 /// RAII object used to optionally suppress diagnostics and side-effects from
995 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000996 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +0000997 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000998 Expr::EvalStatus OldStatus;
999 bool OldIsSpeculativelyEvaluating;
Richard Smith17100ba2012-02-16 02:46:34 +00001000
George Burgess IV8c892b52016-05-25 22:31:54 +00001001 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001002 Info = Other.Info;
1003 OldStatus = Other.OldStatus;
Daniel Jaspera7e061f2017-08-17 06:33:46 +00001004 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001005 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001006 }
1007
1008 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001009 if (!Info)
1010 return;
1011
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001012 Info->EvalStatus = OldStatus;
1013 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
George Burgess IV8c892b52016-05-25 22:31:54 +00001014 }
1015
Richard Smith17100ba2012-02-16 02:46:34 +00001016 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001017 SpeculativeEvaluationRAII() = default;
1018
1019 SpeculativeEvaluationRAII(
1020 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001021 : Info(&Info), OldStatus(Info.EvalStatus),
1022 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
Richard Smith17100ba2012-02-16 02:46:34 +00001023 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001024 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001025 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001026
1027 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1028 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1029 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001030 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001031
1032 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1033 maybeRestoreState();
1034 moveFromAndCancel(std::move(Other));
1035 return *this;
1036 }
1037
1038 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001039 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001040
1041 /// RAII object wrapping a full-expression or block scope, and handling
1042 /// the ending of the lifetime of temporaries created within it.
1043 template<bool IsFullExpression>
1044 class ScopeRAII {
1045 EvalInfo &Info;
1046 unsigned OldStackSize;
1047 public:
1048 ScopeRAII(EvalInfo &Info)
1049 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1050 ~ScopeRAII() {
1051 // Body moved to a static method to encourage the compiler to inline away
1052 // instances of this class.
1053 cleanup(Info, OldStackSize);
1054 }
1055 private:
1056 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1057 unsigned NewEnd = OldStackSize;
1058 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1059 I != N; ++I) {
1060 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1061 // Full-expression cleanup of a lifetime-extended temporary: nothing
1062 // to do, just move this cleanup to the right place in the stack.
1063 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1064 ++NewEnd;
1065 } else {
1066 // End the lifetime of the object.
1067 Info.CleanupStack[I].endLifetime();
1068 }
1069 }
1070 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1071 Info.CleanupStack.end());
1072 }
1073 };
1074 typedef ScopeRAII<false> BlockScopeRAII;
1075 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001076}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001077
Richard Smitha8105bc2012-01-06 16:39:00 +00001078bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1079 CheckSubobjectKind CSK) {
1080 if (Invalid)
1081 return false;
1082 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001083 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001084 << CSK;
1085 setInvalid();
1086 return false;
1087 }
Richard Smith2cd56042017-08-29 01:52:13 +00001088 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1089 // must actually be at least one array element; even a VLA cannot have a
1090 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001091 return true;
1092}
1093
Richard Smith2cd56042017-08-29 01:52:13 +00001094void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1095 const Expr *E) {
1096 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1097 // Do not set the designator as invalid: we can represent this situation,
1098 // and correct handling of __builtin_object_size requires us to do so.
1099}
1100
Richard Smitha8105bc2012-01-06 16:39:00 +00001101void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001102 const Expr *E,
1103 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001104 // If we're complaining, we must be able to statically determine the size of
1105 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001106 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001107 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001108 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001109 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001110 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001111 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001112 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001113 setInvalid();
1114}
1115
Richard Smithf6f003a2011-12-16 19:06:07 +00001116CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1117 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001118 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001119 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1120 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001121 Info.CurrentCall = this;
1122 ++Info.CallStackDepth;
1123}
1124
1125CallStackFrame::~CallStackFrame() {
1126 assert(Info.CurrentCall == this && "calls retired out of order");
1127 --Info.CallStackDepth;
1128 Info.CurrentCall = Caller;
1129}
1130
Richard Smith08d6a2c2013-07-24 07:11:57 +00001131APValue &CallStackFrame::createTemporary(const void *Key,
1132 bool IsLifetimeExtended) {
1133 APValue &Result = Temporaries[Key];
1134 assert(Result.isUninit() && "temporary created multiple times");
1135 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1136 return Result;
1137}
1138
Richard Smith84401042013-06-03 05:03:02 +00001139static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001140
1141void EvalInfo::addCallStack(unsigned Limit) {
1142 // Determine which calls to skip, if any.
1143 unsigned ActiveCalls = CallStackDepth - 1;
1144 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1145 if (Limit && Limit < ActiveCalls) {
1146 SkipStart = Limit / 2 + Limit % 2;
1147 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001148 }
1149
Richard Smithf6f003a2011-12-16 19:06:07 +00001150 // Walk the call stack and add the diagnostics.
1151 unsigned CallIdx = 0;
1152 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1153 Frame = Frame->Caller, ++CallIdx) {
1154 // Skip this call?
1155 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1156 if (CallIdx == SkipStart) {
1157 // Note that we're skipping calls.
1158 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1159 << unsigned(ActiveCalls - Limit);
1160 }
1161 continue;
1162 }
1163
Richard Smith5179eb72016-06-28 19:03:57 +00001164 // Use a different note for an inheriting constructor, because from the
1165 // user's perspective it's not really a function at all.
1166 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1167 if (CD->isInheritingConstructor()) {
1168 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1169 << CD->getParent();
1170 continue;
1171 }
1172 }
1173
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001174 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001175 llvm::raw_svector_ostream Out(Buffer);
1176 describeCall(Frame, Out);
1177 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1178 }
1179}
1180
1181namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001182 struct ComplexValue {
1183 private:
1184 bool IsInt;
1185
1186 public:
1187 APSInt IntReal, IntImag;
1188 APFloat FloatReal, FloatImag;
1189
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001190 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001191
1192 void makeComplexFloat() { IsInt = false; }
1193 bool isComplexFloat() const { return !IsInt; }
1194 APFloat &getComplexFloatReal() { return FloatReal; }
1195 APFloat &getComplexFloatImag() { return FloatImag; }
1196
1197 void makeComplexInt() { IsInt = true; }
1198 bool isComplexInt() const { return IsInt; }
1199 APSInt &getComplexIntReal() { return IntReal; }
1200 APSInt &getComplexIntImag() { return IntImag; }
1201
Richard Smith2e312c82012-03-03 22:46:17 +00001202 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001203 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001204 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001205 else
Richard Smith2e312c82012-03-03 22:46:17 +00001206 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001207 }
Richard Smith2e312c82012-03-03 22:46:17 +00001208 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001209 assert(v.isComplexFloat() || v.isComplexInt());
1210 if (v.isComplexFloat()) {
1211 makeComplexFloat();
1212 FloatReal = v.getComplexFloatReal();
1213 FloatImag = v.getComplexFloatImag();
1214 } else {
1215 makeComplexInt();
1216 IntReal = v.getComplexIntReal();
1217 IntImag = v.getComplexIntImag();
1218 }
1219 }
John McCall93d91dc2010-05-07 17:22:02 +00001220 };
John McCall45d55e42010-05-07 21:00:08 +00001221
1222 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001223 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001224 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001225 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001226 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001227 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001228 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001229
Richard Smithce40ad62011-11-12 22:28:03 +00001230 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001231 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001232 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001233 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001234 SubobjectDesignator &getLValueDesignator() { return Designator; }
1235 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001236 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001237
Richard Smith2e312c82012-03-03 22:46:17 +00001238 void moveInto(APValue &V) const {
1239 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001240 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1241 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001242 else {
1243 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001244 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001245 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001246 }
John McCall45d55e42010-05-07 21:00:08 +00001247 }
Richard Smith2e312c82012-03-03 22:46:17 +00001248 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001249 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001250 Base = V.getLValueBase();
1251 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001252 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001253 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001254 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001255 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001256 }
1257
Tim Northover01503332017-05-26 02:16:00 +00001258 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001259#ifndef NDEBUG
1260 // We only allow a few types of invalid bases. Enforce that here.
1261 if (BInvalid) {
1262 const auto *E = B.get<const Expr *>();
1263 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1264 "Unexpected type of invalid base");
1265 }
1266#endif
1267
Richard Smithce40ad62011-11-12 22:28:03 +00001268 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001269 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001270 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001271 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001272 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001273 IsNullPtr = false;
1274 }
1275
1276 void setNull(QualType PointerTy, uint64_t TargetVal) {
1277 Base = (Expr *)nullptr;
1278 Offset = CharUnits::fromQuantity(TargetVal);
1279 InvalidBase = false;
1280 CallIndex = 0;
1281 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1282 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001283 }
1284
George Burgess IV3a03fab2015-09-04 21:28:13 +00001285 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1286 set(B, I, true);
1287 }
1288
Richard Smitha8105bc2012-01-06 16:39:00 +00001289 // Check that this LValue is not based on a null pointer. If it is, produce
1290 // a diagnostic and mark the designator as invalid.
1291 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1292 CheckSubobjectKind CSK) {
1293 if (Designator.Invalid)
1294 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001295 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001296 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001297 << CSK;
1298 Designator.setInvalid();
1299 return false;
1300 }
1301 return true;
1302 }
1303
1304 // Check this LValue refers to an object. If not, set the designator to be
1305 // invalid and emit a diagnostic.
1306 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001307 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001308 Designator.checkSubobject(Info, E, CSK);
1309 }
1310
1311 void addDecl(EvalInfo &Info, const Expr *E,
1312 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001313 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1314 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001315 }
Richard Smith2cd56042017-08-29 01:52:13 +00001316 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1317 if (!Designator.Entries.empty()) {
1318 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1319 Designator.setInvalid();
1320 return;
1321 }
1322
1323 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
Daniel Jasperffdee092017-05-02 19:21:42 +00001324 Designator.FirstEntryIsAnUnsizedArray = true;
1325 Designator.addUnsizedArrayUnchecked(ElemTy);
George Burgess IVe3763372016-12-22 02:50:20 +00001326 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001327 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001328 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1329 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001330 }
Richard Smith66c96992012-02-18 22:04:06 +00001331 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001332 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1333 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001334 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001335 void clearIsNullPointer() {
1336 IsNullPtr = false;
1337 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001338 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1339 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001340 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1341 // but we're not required to diagnose it and it's valid in C++.)
1342 if (!Index)
1343 return;
1344
1345 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1346 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1347 // offsets.
1348 uint64_t Offset64 = Offset.getQuantity();
1349 uint64_t ElemSize64 = ElementSize.getQuantity();
1350 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1351 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1352
1353 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001354 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001355 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001356 }
1357 void adjustOffset(CharUnits N) {
1358 Offset += N;
1359 if (N.getQuantity())
1360 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001361 }
John McCall45d55e42010-05-07 21:00:08 +00001362 };
Richard Smith027bf112011-11-17 22:56:20 +00001363
1364 struct MemberPtr {
1365 MemberPtr() {}
1366 explicit MemberPtr(const ValueDecl *Decl) :
1367 DeclAndIsDerivedMember(Decl, false), Path() {}
1368
1369 /// The member or (direct or indirect) field referred to by this member
1370 /// pointer, or 0 if this is a null member pointer.
1371 const ValueDecl *getDecl() const {
1372 return DeclAndIsDerivedMember.getPointer();
1373 }
1374 /// Is this actually a member of some type derived from the relevant class?
1375 bool isDerivedMember() const {
1376 return DeclAndIsDerivedMember.getInt();
1377 }
1378 /// Get the class which the declaration actually lives in.
1379 const CXXRecordDecl *getContainingRecord() const {
1380 return cast<CXXRecordDecl>(
1381 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1382 }
1383
Richard Smith2e312c82012-03-03 22:46:17 +00001384 void moveInto(APValue &V) const {
1385 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001386 }
Richard Smith2e312c82012-03-03 22:46:17 +00001387 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001388 assert(V.isMemberPointer());
1389 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1390 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1391 Path.clear();
1392 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1393 Path.insert(Path.end(), P.begin(), P.end());
1394 }
1395
1396 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1397 /// whether the member is a member of some class derived from the class type
1398 /// of the member pointer.
1399 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1400 /// Path - The path of base/derived classes from the member declaration's
1401 /// class (exclusive) to the class type of the member pointer (inclusive).
1402 SmallVector<const CXXRecordDecl*, 4> Path;
1403
1404 /// Perform a cast towards the class of the Decl (either up or down the
1405 /// hierarchy).
1406 bool castBack(const CXXRecordDecl *Class) {
1407 assert(!Path.empty());
1408 const CXXRecordDecl *Expected;
1409 if (Path.size() >= 2)
1410 Expected = Path[Path.size() - 2];
1411 else
1412 Expected = getContainingRecord();
1413 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1414 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1415 // if B does not contain the original member and is not a base or
1416 // derived class of the class containing the original member, the result
1417 // of the cast is undefined.
1418 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1419 // (D::*). We consider that to be a language defect.
1420 return false;
1421 }
1422 Path.pop_back();
1423 return true;
1424 }
1425 /// Perform a base-to-derived member pointer cast.
1426 bool castToDerived(const CXXRecordDecl *Derived) {
1427 if (!getDecl())
1428 return true;
1429 if (!isDerivedMember()) {
1430 Path.push_back(Derived);
1431 return true;
1432 }
1433 if (!castBack(Derived))
1434 return false;
1435 if (Path.empty())
1436 DeclAndIsDerivedMember.setInt(false);
1437 return true;
1438 }
1439 /// Perform a derived-to-base member pointer cast.
1440 bool castToBase(const CXXRecordDecl *Base) {
1441 if (!getDecl())
1442 return true;
1443 if (Path.empty())
1444 DeclAndIsDerivedMember.setInt(true);
1445 if (isDerivedMember()) {
1446 Path.push_back(Base);
1447 return true;
1448 }
1449 return castBack(Base);
1450 }
1451 };
Richard Smith357362d2011-12-13 06:39:58 +00001452
Richard Smith7bb00672012-02-01 01:42:44 +00001453 /// Compare two member pointers, which are assumed to be of the same type.
1454 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1455 if (!LHS.getDecl() || !RHS.getDecl())
1456 return !LHS.getDecl() && !RHS.getDecl();
1457 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1458 return false;
1459 return LHS.Path == RHS.Path;
1460 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001461}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001462
Richard Smith2e312c82012-03-03 22:46:17 +00001463static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001464static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1465 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001466 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001467static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1468 bool InvalidBaseOK = false);
1469static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1470 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001471static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1472 EvalInfo &Info);
1473static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001474static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001475static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001476 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001477static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001478static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001479static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1480 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001481static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001482
1483//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001484// Misc utilities
1485//===----------------------------------------------------------------------===//
1486
Richard Smithd6cc1982017-01-31 02:23:02 +00001487/// Negate an APSInt in place, converting it to a signed form if necessary, and
1488/// preserving its value (by extending by up to one bit as needed).
1489static void negateAsSigned(APSInt &Int) {
1490 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1491 Int = Int.extend(Int.getBitWidth() + 1);
1492 Int.setIsSigned(true);
1493 }
1494 Int = -Int;
1495}
1496
Richard Smith84401042013-06-03 05:03:02 +00001497/// Produce a string describing the given constexpr call.
1498static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1499 unsigned ArgIndex = 0;
1500 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1501 !isa<CXXConstructorDecl>(Frame->Callee) &&
1502 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1503
1504 if (!IsMemberCall)
1505 Out << *Frame->Callee << '(';
1506
1507 if (Frame->This && IsMemberCall) {
1508 APValue Val;
1509 Frame->This->moveInto(Val);
1510 Val.printPretty(Out, Frame->Info.Ctx,
1511 Frame->This->Designator.MostDerivedType);
1512 // FIXME: Add parens around Val if needed.
1513 Out << "->" << *Frame->Callee << '(';
1514 IsMemberCall = false;
1515 }
1516
1517 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1518 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1519 if (ArgIndex > (unsigned)IsMemberCall)
1520 Out << ", ";
1521
1522 const ParmVarDecl *Param = *I;
1523 const APValue &Arg = Frame->Arguments[ArgIndex];
1524 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1525
1526 if (ArgIndex == 0 && IsMemberCall)
1527 Out << "->" << *Frame->Callee << '(';
1528 }
1529
1530 Out << ')';
1531}
1532
Richard Smithd9f663b2013-04-22 15:31:51 +00001533/// Evaluate an expression to see if it had side-effects, and discard its
1534/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001535/// \return \c true if the caller should keep evaluating.
1536static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001537 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001538 if (!Evaluate(Scratch, Info, E))
1539 // We don't need the value, but we might have skipped a side effect here.
1540 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001541 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001542}
1543
Richard Smithd62306a2011-11-10 06:34:14 +00001544/// Should this call expression be treated as a string literal?
1545static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001546 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001547 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1548 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1549}
1550
Richard Smithce40ad62011-11-12 22:28:03 +00001551static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001552 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1553 // constant expression of pointer type that evaluates to...
1554
1555 // ... a null pointer value, or a prvalue core constant expression of type
1556 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001557 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001558
Richard Smithce40ad62011-11-12 22:28:03 +00001559 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1560 // ... the address of an object with static storage duration,
1561 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1562 return VD->hasGlobalStorage();
1563 // ... the address of a function,
1564 return isa<FunctionDecl>(D);
1565 }
1566
1567 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001568 switch (E->getStmtClass()) {
1569 default:
1570 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001571 case Expr::CompoundLiteralExprClass: {
1572 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1573 return CLE->isFileScope() && CLE->isLValue();
1574 }
Richard Smithe6c01442013-06-05 00:46:14 +00001575 case Expr::MaterializeTemporaryExprClass:
1576 // A materialized temporary might have been lifetime-extended to static
1577 // storage duration.
1578 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001579 // A string literal has static storage duration.
1580 case Expr::StringLiteralClass:
1581 case Expr::PredefinedExprClass:
1582 case Expr::ObjCStringLiteralClass:
1583 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001584 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001585 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001586 return true;
1587 case Expr::CallExprClass:
1588 return IsStringLiteralCall(cast<CallExpr>(E));
1589 // For GCC compatibility, &&label has static storage duration.
1590 case Expr::AddrLabelExprClass:
1591 return true;
1592 // A Block literal expression may be used as the initialization value for
1593 // Block variables at global or local static scope.
1594 case Expr::BlockExprClass:
1595 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001596 case Expr::ImplicitValueInitExprClass:
1597 // FIXME:
1598 // We can never form an lvalue with an implicit value initialization as its
1599 // base through expression evaluation, so these only appear in one case: the
1600 // implicit variable declaration we invent when checking whether a constexpr
1601 // constructor can produce a constant expression. We must assume that such
1602 // an expression might be a global lvalue.
1603 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001604 }
John McCall95007602010-05-10 23:27:23 +00001605}
1606
Richard Smithb228a862012-02-15 02:18:13 +00001607static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1608 assert(Base && "no location for a null lvalue");
1609 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1610 if (VD)
1611 Info.Note(VD->getLocation(), diag::note_declared_at);
1612 else
Ted Kremenek28831752012-08-23 20:46:57 +00001613 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001614 diag::note_constexpr_temporary_here);
1615}
1616
Richard Smith80815602011-11-07 05:07:52 +00001617/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001618/// value for an address or reference constant expression. Return true if we
1619/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001620static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1621 QualType Type, const LValue &LVal) {
1622 bool IsReferenceType = Type->isReferenceType();
1623
Richard Smith357362d2011-12-13 06:39:58 +00001624 APValue::LValueBase Base = LVal.getLValueBase();
1625 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1626
Richard Smith0dea49e2012-02-18 04:58:18 +00001627 // Check that the object is a global. Note that the fake 'this' object we
1628 // manufacture when checking potential constant expressions is conservatively
1629 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001630 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001631 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001632 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001633 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001634 << IsReferenceType << !Designator.Entries.empty()
1635 << !!VD << VD;
1636 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001637 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001638 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001639 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001640 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001641 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001642 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001643 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001644 LVal.getLValueCallIndex() == 0) &&
1645 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001646
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001647 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1648 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001649 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001650 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001651 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001652
Hans Wennborg82dd8772014-06-25 22:19:48 +00001653 // A dllimport variable never acts like a constant.
1654 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001655 return false;
1656 }
1657 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1658 // __declspec(dllimport) must be handled very carefully:
1659 // We must never initialize an expression with the thunk in C++.
1660 // Doing otherwise would allow the same id-expression to yield
1661 // different addresses for the same function in different translation
1662 // units. However, this means that we must dynamically initialize the
1663 // expression with the contents of the import address table at runtime.
1664 //
1665 // The C language has no notion of ODR; furthermore, it has no notion of
1666 // dynamic initialization. This means that we are permitted to
1667 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001668 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001669 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001670 }
1671 }
1672
Richard Smitha8105bc2012-01-06 16:39:00 +00001673 // Allow address constant expressions to be past-the-end pointers. This is
1674 // an extension: the standard requires them to point to an object.
1675 if (!IsReferenceType)
1676 return true;
1677
1678 // A reference constant expression must refer to an object.
1679 if (!Base) {
1680 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001681 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001682 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001683 }
1684
Richard Smith357362d2011-12-13 06:39:58 +00001685 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001686 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001687 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001688 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001689 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001690 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001691 }
1692
Richard Smith80815602011-11-07 05:07:52 +00001693 return true;
1694}
1695
Reid Klecknercd016d82017-07-07 22:04:29 +00001696/// Member pointers are constant expressions unless they point to a
1697/// non-virtual dllimport member function.
1698static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1699 SourceLocation Loc,
1700 QualType Type,
1701 const APValue &Value) {
1702 const ValueDecl *Member = Value.getMemberPointerDecl();
1703 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1704 if (!FD)
1705 return true;
1706 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1707}
1708
Richard Smithfddd3842011-12-30 21:15:51 +00001709/// Check that this core constant expression is of literal type, and if not,
1710/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001711static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001712 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001713 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001714 return true;
1715
Richard Smith7525ff62013-05-09 07:14:00 +00001716 // C++1y: A constant initializer for an object o [...] may also invoke
1717 // constexpr constructors for o and its subobjects even if those objects
1718 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001719 //
1720 // C++11 missed this detail for aggregates, so classes like this:
1721 // struct foo_t { union { int i; volatile int j; } u; };
1722 // are not (obviously) initializable like so:
1723 // __attribute__((__require_constant_initialization__))
1724 // static const foo_t x = {{0}};
1725 // because "i" is a subobject with non-literal initialization (due to the
1726 // volatile member of the union). See:
1727 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1728 // Therefore, we use the C++1y behavior.
1729 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001730 return true;
1731
Richard Smithfddd3842011-12-30 21:15:51 +00001732 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001733 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001734 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001735 << E->getType();
1736 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001737 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001738 return false;
1739}
1740
Richard Smith0b0a0b62011-10-29 20:57:55 +00001741/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001742/// constant expression. If not, report an appropriate diagnostic. Does not
1743/// check that the expression is of literal type.
1744static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1745 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001746 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001747 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001748 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001749 return false;
1750 }
1751
Richard Smith77be48a2014-07-31 06:31:19 +00001752 // We allow _Atomic(T) to be initialized from anything that T can be
1753 // initialized from.
1754 if (const AtomicType *AT = Type->getAs<AtomicType>())
1755 Type = AT->getValueType();
1756
Richard Smithb228a862012-02-15 02:18:13 +00001757 // Core issue 1454: For a literal constant expression of array or class type,
1758 // each subobject of its value shall have been initialized by a constant
1759 // expression.
1760 if (Value.isArray()) {
1761 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1762 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1763 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1764 Value.getArrayInitializedElt(I)))
1765 return false;
1766 }
1767 if (!Value.hasArrayFiller())
1768 return true;
1769 return CheckConstantExpression(Info, DiagLoc, EltTy,
1770 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001771 }
Richard Smithb228a862012-02-15 02:18:13 +00001772 if (Value.isUnion() && Value.getUnionField()) {
1773 return CheckConstantExpression(Info, DiagLoc,
1774 Value.getUnionField()->getType(),
1775 Value.getUnionValue());
1776 }
1777 if (Value.isStruct()) {
1778 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1779 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1780 unsigned BaseIndex = 0;
1781 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1782 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1783 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1784 Value.getStructBase(BaseIndex)))
1785 return false;
1786 }
1787 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001788 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001789 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1790 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001791 return false;
1792 }
1793 }
1794
1795 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001796 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001797 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001798 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1799 }
1800
Reid Klecknercd016d82017-07-07 22:04:29 +00001801 if (Value.isMemberPointer())
1802 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1803
Richard Smithb228a862012-02-15 02:18:13 +00001804 // Everything else is fine.
1805 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001806}
1807
Benjamin Kramer8407df72015-03-09 16:47:52 +00001808static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001809 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001810}
1811
1812static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001813 if (Value.CallIndex)
1814 return false;
1815 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1816 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001817}
1818
Richard Smithcecf1842011-11-01 21:06:14 +00001819static bool IsWeakLValue(const LValue &Value) {
1820 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001821 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001822}
1823
David Majnemerb5116032014-12-09 23:32:34 +00001824static bool isZeroSized(const LValue &Value) {
1825 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001826 if (Decl && isa<VarDecl>(Decl)) {
1827 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001828 if (Ty->isArrayType())
1829 return Ty->isIncompleteType() ||
1830 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001831 }
1832 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001833}
1834
Richard Smith2e312c82012-03-03 22:46:17 +00001835static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001836 // A null base expression indicates a null pointer. These are always
1837 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001838 if (!Value.getLValueBase()) {
1839 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001840 return true;
1841 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001842
Richard Smith027bf112011-11-17 22:56:20 +00001843 // We have a non-null base. These are generally known to be true, but if it's
1844 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001845 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001846 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001847 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001848}
1849
Richard Smith2e312c82012-03-03 22:46:17 +00001850static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001851 switch (Val.getKind()) {
1852 case APValue::Uninitialized:
1853 return false;
1854 case APValue::Int:
1855 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001856 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001857 case APValue::Float:
1858 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001859 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001860 case APValue::ComplexInt:
1861 Result = Val.getComplexIntReal().getBoolValue() ||
1862 Val.getComplexIntImag().getBoolValue();
1863 return true;
1864 case APValue::ComplexFloat:
1865 Result = !Val.getComplexFloatReal().isZero() ||
1866 !Val.getComplexFloatImag().isZero();
1867 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001868 case APValue::LValue:
1869 return EvalPointerValueAsBool(Val, Result);
1870 case APValue::MemberPointer:
1871 Result = Val.getMemberPointerDecl();
1872 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001873 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001874 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001875 case APValue::Struct:
1876 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001877 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001878 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001879 }
1880
Richard Smith11562c52011-10-28 17:51:58 +00001881 llvm_unreachable("unknown APValue kind");
1882}
1883
1884static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1885 EvalInfo &Info) {
1886 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001887 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001888 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001889 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001890 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001891}
1892
Richard Smith357362d2011-12-13 06:39:58 +00001893template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001894static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001895 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001896 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001897 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001898 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001899}
1900
1901static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1902 QualType SrcType, const APFloat &Value,
1903 QualType DestType, APSInt &Result) {
1904 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001905 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001906 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001907
Richard Smith357362d2011-12-13 06:39:58 +00001908 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001909 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001910 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1911 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001912 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001913 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001914}
1915
Richard Smith357362d2011-12-13 06:39:58 +00001916static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1917 QualType SrcType, QualType DestType,
1918 APFloat &Result) {
1919 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001920 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001921 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1922 APFloat::rmNearestTiesToEven, &ignored)
1923 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001924 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001925 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001926}
1927
Richard Smith911e1422012-01-30 22:27:01 +00001928static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1929 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001930 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001931 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001932 APSInt Result = Value;
1933 // Figure out if this is a truncate, extend or noop cast.
1934 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001935 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001936 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001937 return Result;
1938}
1939
Richard Smith357362d2011-12-13 06:39:58 +00001940static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1941 QualType SrcType, const APSInt &Value,
1942 QualType DestType, APFloat &Result) {
1943 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1944 if (Result.convertFromAPInt(Value, Value.isSigned(),
1945 APFloat::rmNearestTiesToEven)
1946 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001947 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001948 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001949}
1950
Richard Smith49ca8aa2013-08-06 07:09:20 +00001951static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1952 APValue &Value, const FieldDecl *FD) {
1953 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1954
1955 if (!Value.isInt()) {
1956 // Trying to store a pointer-cast-to-integer into a bitfield.
1957 // FIXME: In this case, we should provide the diagnostic for casting
1958 // a pointer to an integer.
1959 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001960 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001961 return false;
1962 }
1963
1964 APSInt &Int = Value.getInt();
1965 unsigned OldBitWidth = Int.getBitWidth();
1966 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1967 if (NewBitWidth < OldBitWidth)
1968 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1969 return true;
1970}
1971
Eli Friedman803acb32011-12-22 03:51:45 +00001972static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1973 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001974 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001975 if (!Evaluate(SVal, Info, E))
1976 return false;
1977 if (SVal.isInt()) {
1978 Res = SVal.getInt();
1979 return true;
1980 }
1981 if (SVal.isFloat()) {
1982 Res = SVal.getFloat().bitcastToAPInt();
1983 return true;
1984 }
1985 if (SVal.isVector()) {
1986 QualType VecTy = E->getType();
1987 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1988 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1989 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1990 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1991 Res = llvm::APInt::getNullValue(VecSize);
1992 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1993 APValue &Elt = SVal.getVectorElt(i);
1994 llvm::APInt EltAsInt;
1995 if (Elt.isInt()) {
1996 EltAsInt = Elt.getInt();
1997 } else if (Elt.isFloat()) {
1998 EltAsInt = Elt.getFloat().bitcastToAPInt();
1999 } else {
2000 // Don't try to handle vectors of anything other than int or float
2001 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002002 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002003 return false;
2004 }
2005 unsigned BaseEltSize = EltAsInt.getBitWidth();
2006 if (BigEndian)
2007 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2008 else
2009 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2010 }
2011 return true;
2012 }
2013 // Give up if the input isn't an int, float, or vector. For example, we
2014 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002015 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002016 return false;
2017}
2018
Richard Smith43e77732013-05-07 04:50:00 +00002019/// Perform the given integer operation, which is known to need at most BitWidth
2020/// bits, and check for overflow in the original type (if that type was not an
2021/// unsigned type).
2022template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002023static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2024 const APSInt &LHS, const APSInt &RHS,
2025 unsigned BitWidth, Operation Op,
2026 APSInt &Result) {
2027 if (LHS.isUnsigned()) {
2028 Result = Op(LHS, RHS);
2029 return true;
2030 }
Richard Smith43e77732013-05-07 04:50:00 +00002031
2032 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002033 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002034 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002035 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002036 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002037 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002038 << Result.toString(10) << E->getType();
2039 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002040 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002041 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002042 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002043}
2044
2045/// Perform the given binary integer operation.
2046static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2047 BinaryOperatorKind Opcode, APSInt RHS,
2048 APSInt &Result) {
2049 switch (Opcode) {
2050 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002051 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002052 return false;
2053 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002054 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2055 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002056 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002057 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2058 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002059 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002060 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2061 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002062 case BO_And: Result = LHS & RHS; return true;
2063 case BO_Xor: Result = LHS ^ RHS; return true;
2064 case BO_Or: Result = LHS | RHS; return true;
2065 case BO_Div:
2066 case BO_Rem:
2067 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002068 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002069 return false;
2070 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002071 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2072 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2073 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002074 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2075 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002076 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2077 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002078 return true;
2079 case BO_Shl: {
2080 if (Info.getLangOpts().OpenCL)
2081 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2082 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2083 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2084 RHS.isUnsigned());
2085 else if (RHS.isSigned() && RHS.isNegative()) {
2086 // During constant-folding, a negative shift is an opposite shift. Such
2087 // a shift is not a constant expression.
2088 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2089 RHS = -RHS;
2090 goto shift_right;
2091 }
2092 shift_left:
2093 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2094 // the shifted type.
2095 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2096 if (SA != RHS) {
2097 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2098 << RHS << E->getType() << LHS.getBitWidth();
2099 } else if (LHS.isSigned()) {
2100 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2101 // operand, and must not overflow the corresponding unsigned type.
2102 if (LHS.isNegative())
2103 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2104 else if (LHS.countLeadingZeros() < SA)
2105 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2106 }
2107 Result = LHS << SA;
2108 return true;
2109 }
2110 case BO_Shr: {
2111 if (Info.getLangOpts().OpenCL)
2112 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2113 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2114 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2115 RHS.isUnsigned());
2116 else if (RHS.isSigned() && RHS.isNegative()) {
2117 // During constant-folding, a negative shift is an opposite shift. Such a
2118 // shift is not a constant expression.
2119 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2120 RHS = -RHS;
2121 goto shift_left;
2122 }
2123 shift_right:
2124 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2125 // shifted type.
2126 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2127 if (SA != RHS)
2128 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2129 << RHS << E->getType() << LHS.getBitWidth();
2130 Result = LHS >> SA;
2131 return true;
2132 }
2133
2134 case BO_LT: Result = LHS < RHS; return true;
2135 case BO_GT: Result = LHS > RHS; return true;
2136 case BO_LE: Result = LHS <= RHS; return true;
2137 case BO_GE: Result = LHS >= RHS; return true;
2138 case BO_EQ: Result = LHS == RHS; return true;
2139 case BO_NE: Result = LHS != RHS; return true;
2140 }
2141}
2142
Richard Smith861b5b52013-05-07 23:34:45 +00002143/// Perform the given binary floating-point operation, in-place, on LHS.
2144static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2145 APFloat &LHS, BinaryOperatorKind Opcode,
2146 const APFloat &RHS) {
2147 switch (Opcode) {
2148 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002149 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002150 return false;
2151 case BO_Mul:
2152 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2153 break;
2154 case BO_Add:
2155 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2156 break;
2157 case BO_Sub:
2158 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2159 break;
2160 case BO_Div:
2161 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2162 break;
2163 }
2164
Richard Smith0c6124b2015-12-03 01:36:22 +00002165 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002166 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002167 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002168 }
Richard Smith861b5b52013-05-07 23:34:45 +00002169 return true;
2170}
2171
Richard Smitha8105bc2012-01-06 16:39:00 +00002172/// Cast an lvalue referring to a base subobject to a derived class, by
2173/// truncating the lvalue's path to the given length.
2174static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2175 const RecordDecl *TruncatedType,
2176 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002177 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002178
2179 // Check we actually point to a derived class object.
2180 if (TruncatedElements == D.Entries.size())
2181 return true;
2182 assert(TruncatedElements >= D.MostDerivedPathLength &&
2183 "not casting to a derived class");
2184 if (!Result.checkSubobject(Info, E, CSK_Derived))
2185 return false;
2186
2187 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002188 const RecordDecl *RD = TruncatedType;
2189 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002190 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002191 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2192 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002193 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002194 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002195 else
Richard Smithd62306a2011-11-10 06:34:14 +00002196 Result.Offset -= Layout.getBaseClassOffset(Base);
2197 RD = Base;
2198 }
Richard Smith027bf112011-11-17 22:56:20 +00002199 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002200 return true;
2201}
2202
John McCalld7bca762012-05-01 00:38:49 +00002203static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002204 const CXXRecordDecl *Derived,
2205 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002206 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002207 if (!RL) {
2208 if (Derived->isInvalidDecl()) return false;
2209 RL = &Info.Ctx.getASTRecordLayout(Derived);
2210 }
2211
Richard Smithd62306a2011-11-10 06:34:14 +00002212 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002213 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002214 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002215}
2216
Richard Smitha8105bc2012-01-06 16:39:00 +00002217static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002218 const CXXRecordDecl *DerivedDecl,
2219 const CXXBaseSpecifier *Base) {
2220 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2221
John McCalld7bca762012-05-01 00:38:49 +00002222 if (!Base->isVirtual())
2223 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002224
Richard Smitha8105bc2012-01-06 16:39:00 +00002225 SubobjectDesignator &D = Obj.Designator;
2226 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002227 return false;
2228
Richard Smitha8105bc2012-01-06 16:39:00 +00002229 // Extract most-derived object and corresponding type.
2230 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2231 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2232 return false;
2233
2234 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002235 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002236 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2237 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002238 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002239 return true;
2240}
2241
Richard Smith84401042013-06-03 05:03:02 +00002242static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2243 QualType Type, LValue &Result) {
2244 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2245 PathE = E->path_end();
2246 PathI != PathE; ++PathI) {
2247 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2248 *PathI))
2249 return false;
2250 Type = (*PathI)->getType();
2251 }
2252 return true;
2253}
2254
Richard Smithd62306a2011-11-10 06:34:14 +00002255/// Update LVal to refer to the given field, which must be a member of the type
2256/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002257static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002258 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002259 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002260 if (!RL) {
2261 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002262 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002263 }
Richard Smithd62306a2011-11-10 06:34:14 +00002264
2265 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002266 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002267 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002268 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002269}
2270
Richard Smith1b78b3d2012-01-25 22:15:11 +00002271/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002272static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002273 LValue &LVal,
2274 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002275 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002276 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002277 return false;
2278 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002279}
2280
Richard Smithd62306a2011-11-10 06:34:14 +00002281/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002282static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2283 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002284 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2285 // extension.
2286 if (Type->isVoidType() || Type->isFunctionType()) {
2287 Size = CharUnits::One();
2288 return true;
2289 }
2290
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002291 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002292 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002293 return false;
2294 }
2295
Richard Smithd62306a2011-11-10 06:34:14 +00002296 if (!Type->isConstantSizeType()) {
2297 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002298 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002299 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002300 return false;
2301 }
2302
2303 Size = Info.Ctx.getTypeSizeInChars(Type);
2304 return true;
2305}
2306
2307/// Update a pointer value to model pointer arithmetic.
2308/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002309/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002310/// \param LVal - The pointer value to be updated.
2311/// \param EltTy - The pointee type represented by LVal.
2312/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002313static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2314 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002315 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002316 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002317 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002318 return false;
2319
Yaxun Liu402804b2016-12-15 08:09:08 +00002320 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002321 return true;
2322}
2323
Richard Smithd6cc1982017-01-31 02:23:02 +00002324static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2325 LValue &LVal, QualType EltTy,
2326 int64_t Adjustment) {
2327 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2328 APSInt::get(Adjustment));
2329}
2330
Richard Smith66c96992012-02-18 22:04:06 +00002331/// Update an lvalue to refer to a component of a complex number.
2332/// \param Info - Information about the ongoing evaluation.
2333/// \param LVal - The lvalue to be updated.
2334/// \param EltTy - The complex number's component type.
2335/// \param Imag - False for the real component, true for the imaginary.
2336static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2337 LValue &LVal, QualType EltTy,
2338 bool Imag) {
2339 if (Imag) {
2340 CharUnits SizeOfComponent;
2341 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2342 return false;
2343 LVal.Offset += SizeOfComponent;
2344 }
2345 LVal.addComplex(Info, E, EltTy, Imag);
2346 return true;
2347}
2348
Faisal Vali051e3a22017-02-16 04:12:21 +00002349static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2350 QualType Type, const LValue &LVal,
2351 APValue &RVal);
2352
Richard Smith27908702011-10-24 17:54:18 +00002353/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002354///
2355/// \param Info Information about the ongoing evaluation.
2356/// \param E An expression to be used when printing diagnostics.
2357/// \param VD The variable whose initializer should be obtained.
2358/// \param Frame The frame in which the variable was created. Must be null
2359/// if this variable is not local to the evaluation.
2360/// \param Result Filled in with a pointer to the value of the variable.
2361static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2362 const VarDecl *VD, CallStackFrame *Frame,
2363 APValue *&Result) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002364
Richard Smith254a73d2011-10-28 22:34:42 +00002365 // If this is a parameter to an active constexpr function call, perform
2366 // argument substitution.
2367 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002368 // Assume arguments of a potential constant expression are unknown
2369 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002370 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002371 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002372 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002373 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002374 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002375 }
Richard Smith3229b742013-05-05 21:17:10 +00002376 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002377 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002378 }
Richard Smith27908702011-10-24 17:54:18 +00002379
Richard Smithd9f663b2013-04-22 15:31:51 +00002380 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002381 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002382 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002383 if (!Result) {
2384 // Assume variables referenced within a lambda's call operator that were
2385 // not declared within the call operator are captures and during checking
2386 // of a potential constant expression, assume they are unknown constant
2387 // expressions.
2388 assert(isLambdaCallOperator(Frame->Callee) &&
2389 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2390 "missing value for local variable");
2391 if (Info.checkingPotentialConstantExpression())
2392 return false;
2393 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002394 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002395 diag::note_unimplemented_constexpr_lambda_feature_ast)
2396 << "captures not currently allowed";
2397 return false;
2398 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002399 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002400 }
2401
Richard Smithd0b4dd62011-12-19 06:19:21 +00002402 // Dig out the initializer, and use the declaration which it's attached to.
2403 const Expr *Init = VD->getAnyInitializer(VD);
2404 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002405 // If we're checking a potential constant expression, the variable could be
2406 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002407 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002408 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002409 return false;
2410 }
2411
Richard Smithd62306a2011-11-10 06:34:14 +00002412 // If we're currently evaluating the initializer of this declaration, use that
2413 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002414 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002415 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002416 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002417 }
2418
Richard Smithcecf1842011-11-01 21:06:14 +00002419 // Never evaluate the initializer of a weak variable. We can't be sure that
2420 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002421 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002422 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002423 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002424 }
Richard Smithcecf1842011-11-01 21:06:14 +00002425
Richard Smithd0b4dd62011-12-19 06:19:21 +00002426 // Check that we can fold the initializer. In C++, we will have already done
2427 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002428 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002429 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002430 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002431 Notes.size() + 1) << VD;
2432 Info.Note(VD->getLocation(), diag::note_declared_at);
2433 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002434 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002435 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002436 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002437 Notes.size() + 1) << VD;
2438 Info.Note(VD->getLocation(), diag::note_declared_at);
2439 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002440 }
Richard Smith27908702011-10-24 17:54:18 +00002441
Richard Smith3229b742013-05-05 21:17:10 +00002442 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002443 return true;
Richard Smith27908702011-10-24 17:54:18 +00002444}
2445
Richard Smith11562c52011-10-28 17:51:58 +00002446static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002447 Qualifiers Quals = T.getQualifiers();
2448 return Quals.hasConst() && !Quals.hasVolatile();
2449}
2450
Richard Smithe97cbd72011-11-11 04:05:33 +00002451/// Get the base index of the given base class within an APValue representing
2452/// the given derived class.
2453static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2454 const CXXRecordDecl *Base) {
2455 Base = Base->getCanonicalDecl();
2456 unsigned Index = 0;
2457 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2458 E = Derived->bases_end(); I != E; ++I, ++Index) {
2459 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2460 return Index;
2461 }
2462
2463 llvm_unreachable("base class missing from derived class's bases list");
2464}
2465
Richard Smith3da88fa2013-04-26 14:36:30 +00002466/// Extract the value of a character from a string literal.
2467static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2468 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002469 // FIXME: Support MakeStringConstant
2470 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2471 std::string Str;
2472 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2473 assert(Index <= Str.size() && "Index too large");
2474 return APSInt::getUnsigned(Str.c_str()[Index]);
2475 }
2476
Alexey Bataevec474782014-10-09 08:45:04 +00002477 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2478 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002479 const StringLiteral *S = cast<StringLiteral>(Lit);
2480 const ConstantArrayType *CAT =
2481 Info.Ctx.getAsConstantArrayType(S->getType());
2482 assert(CAT && "string literal isn't an array");
2483 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002484 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002485
2486 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002487 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002488 if (Index < S->getLength())
2489 Value = S->getCodeUnit(Index);
2490 return Value;
2491}
2492
Richard Smith3da88fa2013-04-26 14:36:30 +00002493// Expand a string literal into an array of characters.
2494static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2495 APValue &Result) {
2496 const StringLiteral *S = cast<StringLiteral>(Lit);
2497 const ConstantArrayType *CAT =
2498 Info.Ctx.getAsConstantArrayType(S->getType());
2499 assert(CAT && "string literal isn't an array");
2500 QualType CharType = CAT->getElementType();
2501 assert(CharType->isIntegerType() && "unexpected character type");
2502
2503 unsigned Elts = CAT->getSize().getZExtValue();
2504 Result = APValue(APValue::UninitArray(),
2505 std::min(S->getLength(), Elts), Elts);
2506 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2507 CharType->isUnsignedIntegerType());
2508 if (Result.hasArrayFiller())
2509 Result.getArrayFiller() = APValue(Value);
2510 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2511 Value = S->getCodeUnit(I);
2512 Result.getArrayInitializedElt(I) = APValue(Value);
2513 }
2514}
2515
2516// Expand an array so that it has more than Index filled elements.
2517static void expandArray(APValue &Array, unsigned Index) {
2518 unsigned Size = Array.getArraySize();
2519 assert(Index < Size);
2520
2521 // Always at least double the number of elements for which we store a value.
2522 unsigned OldElts = Array.getArrayInitializedElts();
2523 unsigned NewElts = std::max(Index+1, OldElts * 2);
2524 NewElts = std::min(Size, std::max(NewElts, 8u));
2525
2526 // Copy the data across.
2527 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2528 for (unsigned I = 0; I != OldElts; ++I)
2529 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2530 for (unsigned I = OldElts; I != NewElts; ++I)
2531 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2532 if (NewValue.hasArrayFiller())
2533 NewValue.getArrayFiller() = Array.getArrayFiller();
2534 Array.swap(NewValue);
2535}
2536
Richard Smithb01fe402014-09-16 01:24:02 +00002537/// Determine whether a type would actually be read by an lvalue-to-rvalue
2538/// conversion. If it's of class type, we may assume that the copy operation
2539/// is trivial. Note that this is never true for a union type with fields
2540/// (because the copy always "reads" the active member) and always true for
2541/// a non-class type.
2542static bool isReadByLvalueToRvalueConversion(QualType T) {
2543 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2544 if (!RD || (RD->isUnion() && !RD->field_empty()))
2545 return true;
2546 if (RD->isEmpty())
2547 return false;
2548
2549 for (auto *Field : RD->fields())
2550 if (isReadByLvalueToRvalueConversion(Field->getType()))
2551 return true;
2552
2553 for (auto &BaseSpec : RD->bases())
2554 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2555 return true;
2556
2557 return false;
2558}
2559
2560/// Diagnose an attempt to read from any unreadable field within the specified
2561/// type, which might be a class type.
2562static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2563 QualType T) {
2564 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2565 if (!RD)
2566 return false;
2567
2568 if (!RD->hasMutableFields())
2569 return false;
2570
2571 for (auto *Field : RD->fields()) {
2572 // If we're actually going to read this field in some way, then it can't
2573 // be mutable. If we're in a union, then assigning to a mutable field
2574 // (even an empty one) can change the active member, so that's not OK.
2575 // FIXME: Add core issue number for the union case.
2576 if (Field->isMutable() &&
2577 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002578 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002579 Info.Note(Field->getLocation(), diag::note_declared_at);
2580 return true;
2581 }
2582
2583 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2584 return true;
2585 }
2586
2587 for (auto &BaseSpec : RD->bases())
2588 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2589 return true;
2590
2591 // All mutable fields were empty, and thus not actually read.
2592 return false;
2593}
2594
Richard Smith861b5b52013-05-07 23:34:45 +00002595/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002596enum AccessKinds {
2597 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002598 AK_Assign,
2599 AK_Increment,
2600 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002601};
2602
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002603namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002604/// A handle to a complete object (an object that is not a subobject of
2605/// another object).
2606struct CompleteObject {
2607 /// The value of the complete object.
2608 APValue *Value;
2609 /// The type of the complete object.
2610 QualType Type;
2611
Craig Topper36250ad2014-05-12 05:36:57 +00002612 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002613 CompleteObject(APValue *Value, QualType Type)
2614 : Value(Value), Type(Type) {
2615 assert(Value && "missing value for complete object");
2616 }
2617
Aaron Ballman67347662015-02-15 22:00:28 +00002618 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002619};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002620} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002621
Richard Smith3da88fa2013-04-26 14:36:30 +00002622/// Find the designated sub-object of an rvalue.
2623template<typename SubobjectHandler>
2624typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002625findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002626 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002627 if (Sub.Invalid)
2628 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002629 return handler.failed();
Richard Smith2cd56042017-08-29 01:52:13 +00002630 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002631 if (Info.getLangOpts().CPlusPlus11)
Richard Smith2cd56042017-08-29 01:52:13 +00002632 Info.FFDiag(E, Sub.isOnePastTheEnd()
2633 ? diag::note_constexpr_access_past_end
2634 : diag::note_constexpr_access_unsized_array)
2635 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002636 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002637 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002638 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002639 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002640
Richard Smith3229b742013-05-05 21:17:10 +00002641 APValue *O = Obj.Value;
2642 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002643 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002644
Richard Smithd62306a2011-11-10 06:34:14 +00002645 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002646 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2647 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002648 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002649 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002650 return handler.failed();
2651 }
2652
Richard Smith49ca8aa2013-08-06 07:09:20 +00002653 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002654 // If we are reading an object of class type, there may still be more
2655 // things we need to check: if there are any mutable subobjects, we
2656 // cannot perform this read. (This only happens when performing a trivial
2657 // copy or assignment.)
2658 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2659 diagnoseUnreadableFields(Info, E, ObjType))
2660 return handler.failed();
2661
Richard Smith49ca8aa2013-08-06 07:09:20 +00002662 if (!handler.found(*O, ObjType))
2663 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002664
Richard Smith49ca8aa2013-08-06 07:09:20 +00002665 // If we modified a bit-field, truncate it to the right width.
2666 if (handler.AccessKind != AK_Read &&
2667 LastField && LastField->isBitField() &&
2668 !truncateBitfieldValue(Info, E, *O, LastField))
2669 return false;
2670
2671 return true;
2672 }
2673
Craig Topper36250ad2014-05-12 05:36:57 +00002674 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002675 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002676 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002677 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002678 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002679 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002680 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002681 // Note, it should not be possible to form a pointer with a valid
2682 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002683 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002684 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002685 << handler.AccessKind;
2686 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002687 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002688 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002689 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002690
2691 ObjType = CAT->getElementType();
2692
Richard Smith14a94132012-02-17 03:35:37 +00002693 // An array object is represented as either an Array APValue or as an
2694 // LValue which refers to a string literal.
2695 if (O->isLValue()) {
2696 assert(I == N - 1 && "extracting subobject of character?");
2697 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002698 if (handler.AccessKind != AK_Read)
2699 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2700 *O);
2701 else
2702 return handler.foundString(*O, ObjType, Index);
2703 }
2704
2705 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002706 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002707 else if (handler.AccessKind != AK_Read) {
2708 expandArray(*O, Index);
2709 O = &O->getArrayInitializedElt(Index);
2710 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002711 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002712 } else if (ObjType->isAnyComplexType()) {
2713 // Next subobject is a complex number.
2714 uint64_t Index = Sub.Entries[I].ArrayIndex;
2715 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002716 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002717 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002718 << handler.AccessKind;
2719 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002720 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002721 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002722 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002723
2724 bool WasConstQualified = ObjType.isConstQualified();
2725 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2726 if (WasConstQualified)
2727 ObjType.addConst();
2728
Richard Smith66c96992012-02-18 22:04:06 +00002729 assert(I == N - 1 && "extracting subobject of scalar?");
2730 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002731 return handler.found(Index ? O->getComplexIntImag()
2732 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002733 } else {
2734 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002735 return handler.found(Index ? O->getComplexFloatImag()
2736 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002737 }
Richard Smithd62306a2011-11-10 06:34:14 +00002738 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002739 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002740 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002741 << Field;
2742 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002743 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002744 }
2745
Richard Smithd62306a2011-11-10 06:34:14 +00002746 // Next subobject is a class, struct or union field.
2747 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2748 if (RD->isUnion()) {
2749 const FieldDecl *UnionField = O->getUnionField();
2750 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002751 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002752 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002753 << handler.AccessKind << Field << !UnionField << UnionField;
2754 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002755 }
Richard Smithd62306a2011-11-10 06:34:14 +00002756 O = &O->getUnionValue();
2757 } else
2758 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002759
2760 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002761 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002762 if (WasConstQualified && !Field->isMutable())
2763 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002764
2765 if (ObjType.isVolatileQualified()) {
2766 if (Info.getLangOpts().CPlusPlus) {
2767 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002768 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002769 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002770 Info.Note(Field->getLocation(), diag::note_declared_at);
2771 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002772 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002773 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002774 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002775 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002776
2777 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002778 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002779 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002780 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2781 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2782 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002783
2784 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002785 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002786 if (WasConstQualified)
2787 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002788 }
2789 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002790}
2791
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002792namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002793struct ExtractSubobjectHandler {
2794 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002795 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002796
2797 static const AccessKinds AccessKind = AK_Read;
2798
2799 typedef bool result_type;
2800 bool failed() { return false; }
2801 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002802 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002803 return true;
2804 }
2805 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002806 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002807 return true;
2808 }
2809 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002810 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002811 return true;
2812 }
2813 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002814 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002815 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2816 return true;
2817 }
2818};
Richard Smith3229b742013-05-05 21:17:10 +00002819} // end anonymous namespace
2820
Richard Smith3da88fa2013-04-26 14:36:30 +00002821const AccessKinds ExtractSubobjectHandler::AccessKind;
2822
2823/// Extract the designated sub-object of an rvalue.
2824static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002825 const CompleteObject &Obj,
2826 const SubobjectDesignator &Sub,
2827 APValue &Result) {
2828 ExtractSubobjectHandler Handler = { Info, Result };
2829 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002830}
2831
Richard Smith3229b742013-05-05 21:17:10 +00002832namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002833struct ModifySubobjectHandler {
2834 EvalInfo &Info;
2835 APValue &NewVal;
2836 const Expr *E;
2837
2838 typedef bool result_type;
2839 static const AccessKinds AccessKind = AK_Assign;
2840
2841 bool checkConst(QualType QT) {
2842 // Assigning to a const object has undefined behavior.
2843 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002844 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002845 return false;
2846 }
2847 return true;
2848 }
2849
2850 bool failed() { return false; }
2851 bool found(APValue &Subobj, QualType SubobjType) {
2852 if (!checkConst(SubobjType))
2853 return false;
2854 // We've been given ownership of NewVal, so just swap it in.
2855 Subobj.swap(NewVal);
2856 return true;
2857 }
2858 bool found(APSInt &Value, QualType SubobjType) {
2859 if (!checkConst(SubobjType))
2860 return false;
2861 if (!NewVal.isInt()) {
2862 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002863 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002864 return false;
2865 }
2866 Value = NewVal.getInt();
2867 return true;
2868 }
2869 bool found(APFloat &Value, QualType SubobjType) {
2870 if (!checkConst(SubobjType))
2871 return false;
2872 Value = NewVal.getFloat();
2873 return true;
2874 }
2875 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2876 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2877 }
2878};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002879} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002880
Richard Smith3229b742013-05-05 21:17:10 +00002881const AccessKinds ModifySubobjectHandler::AccessKind;
2882
Richard Smith3da88fa2013-04-26 14:36:30 +00002883/// Update the designated sub-object of an rvalue to the given value.
2884static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002885 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002886 const SubobjectDesignator &Sub,
2887 APValue &NewVal) {
2888 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002889 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002890}
2891
Richard Smith84f6dcf2012-02-02 01:16:57 +00002892/// Find the position where two subobject designators diverge, or equivalently
2893/// the length of the common initial subsequence.
2894static unsigned FindDesignatorMismatch(QualType ObjType,
2895 const SubobjectDesignator &A,
2896 const SubobjectDesignator &B,
2897 bool &WasArrayIndex) {
2898 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2899 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002900 if (!ObjType.isNull() &&
2901 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002902 // Next subobject is an array element.
2903 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2904 WasArrayIndex = true;
2905 return I;
2906 }
Richard Smith66c96992012-02-18 22:04:06 +00002907 if (ObjType->isAnyComplexType())
2908 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2909 else
2910 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002911 } else {
2912 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2913 WasArrayIndex = false;
2914 return I;
2915 }
2916 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2917 // Next subobject is a field.
2918 ObjType = FD->getType();
2919 else
2920 // Next subobject is a base class.
2921 ObjType = QualType();
2922 }
2923 }
2924 WasArrayIndex = false;
2925 return I;
2926}
2927
2928/// Determine whether the given subobject designators refer to elements of the
2929/// same array object.
2930static bool AreElementsOfSameArray(QualType ObjType,
2931 const SubobjectDesignator &A,
2932 const SubobjectDesignator &B) {
2933 if (A.Entries.size() != B.Entries.size())
2934 return false;
2935
George Burgess IVa51c4072015-10-16 01:49:01 +00002936 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002937 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2938 // A is a subobject of the array element.
2939 return false;
2940
2941 // If A (and B) designates an array element, the last entry will be the array
2942 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2943 // of length 1' case, and the entire path must match.
2944 bool WasArrayIndex;
2945 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2946 return CommonLength >= A.Entries.size() - IsArray;
2947}
2948
Richard Smith3229b742013-05-05 21:17:10 +00002949/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002950static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2951 AccessKinds AK, const LValue &LVal,
2952 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002953 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002954 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002955 return CompleteObject();
2956 }
2957
Craig Topper36250ad2014-05-12 05:36:57 +00002958 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002959 if (LVal.CallIndex) {
2960 Frame = Info.getCallFrame(LVal.CallIndex);
2961 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002962 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002963 << AK << LVal.Base.is<const ValueDecl*>();
2964 NoteLValueLocation(Info, LVal.Base);
2965 return CompleteObject();
2966 }
Richard Smith3229b742013-05-05 21:17:10 +00002967 }
2968
2969 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2970 // is not a constant expression (even if the object is non-volatile). We also
2971 // apply this rule to C++98, in order to conform to the expected 'volatile'
2972 // semantics.
2973 if (LValType.isVolatileQualified()) {
2974 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002975 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002976 << AK << LValType;
2977 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002978 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002979 return CompleteObject();
2980 }
2981
2982 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002983 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002984 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002985
2986 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2987 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2988 // In C++11, constexpr, non-volatile variables initialized with constant
2989 // expressions are constant expressions too. Inside constexpr functions,
2990 // parameters are constant expressions even if they're non-const.
2991 // In C++1y, objects local to a constant expression (those with a Frame) are
2992 // both readable and writable inside constant expressions.
2993 // In C, such things can also be folded, although they are not ICEs.
2994 const VarDecl *VD = dyn_cast<VarDecl>(D);
2995 if (VD) {
2996 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2997 VD = VDef;
2998 }
2999 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003000 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003001 return CompleteObject();
3002 }
3003
3004 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003005 if (BaseType.isVolatileQualified()) {
3006 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003007 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003008 << AK << 1 << VD;
3009 Info.Note(VD->getLocation(), diag::note_declared_at);
3010 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003011 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003012 }
3013 return CompleteObject();
3014 }
3015
3016 // Unless we're looking at a local variable or argument in a constexpr call,
3017 // the variable we're reading must be const.
3018 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003019 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003020 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3021 // OK, we can read and modify an object if we're in the process of
3022 // evaluating its initializer, because its lifetime began in this
3023 // evaluation.
3024 } else if (AK != AK_Read) {
3025 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003026 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003027 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003028 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003029 // OK, we can read this variable.
3030 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003031 // In OpenCL if a variable is in constant address space it is a const value.
3032 if (!(BaseType.isConstQualified() ||
3033 (Info.getLangOpts().OpenCL &&
3034 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003035 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003036 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003037 Info.Note(VD->getLocation(), diag::note_declared_at);
3038 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003039 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003040 }
3041 return CompleteObject();
3042 }
3043 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3044 // We support folding of const floating-point types, in order to make
3045 // static const data members of such types (supported as an extension)
3046 // more useful.
3047 if (Info.getLangOpts().CPlusPlus11) {
3048 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3049 Info.Note(VD->getLocation(), diag::note_declared_at);
3050 } else {
3051 Info.CCEDiag(E);
3052 }
George Burgess IVb5316982016-12-27 05:33:20 +00003053 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3054 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3055 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003056 } else {
3057 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003058 if (Info.checkingPotentialConstantExpression() &&
3059 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3060 // The definition of this variable could be constexpr. We can't
3061 // access it right now, but may be able to in future.
3062 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003063 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003064 Info.Note(VD->getLocation(), diag::note_declared_at);
3065 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003066 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003067 }
3068 return CompleteObject();
3069 }
3070 }
3071
3072 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3073 return CompleteObject();
3074 } else {
3075 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3076
3077 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003078 if (const MaterializeTemporaryExpr *MTE =
3079 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3080 assert(MTE->getStorageDuration() == SD_Static &&
3081 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003082
Richard Smithe6c01442013-06-05 00:46:14 +00003083 // Per C++1y [expr.const]p2:
3084 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3085 // - a [...] glvalue of integral or enumeration type that refers to
3086 // a non-volatile const object [...]
3087 // [...]
3088 // - a [...] glvalue of literal type that refers to a non-volatile
3089 // object whose lifetime began within the evaluation of e.
3090 //
3091 // C++11 misses the 'began within the evaluation of e' check and
3092 // instead allows all temporaries, including things like:
3093 // int &&r = 1;
3094 // int x = ++r;
3095 // constexpr int k = r;
3096 // Therefore we use the C++1y rules in C++11 too.
3097 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3098 const ValueDecl *ED = MTE->getExtendingDecl();
3099 if (!(BaseType.isConstQualified() &&
3100 BaseType->isIntegralOrEnumerationType()) &&
3101 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003102 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003103 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3104 return CompleteObject();
3105 }
3106
3107 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3108 assert(BaseVal && "got reference to unevaluated temporary");
3109 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003110 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003111 return CompleteObject();
3112 }
3113 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003114 BaseVal = Frame->getTemporary(Base);
3115 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003116 }
Richard Smith3229b742013-05-05 21:17:10 +00003117
3118 // Volatile temporary objects cannot be accessed in constant expressions.
3119 if (BaseType.isVolatileQualified()) {
3120 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003121 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003122 << AK << 0;
3123 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3124 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003125 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003126 }
3127 return CompleteObject();
3128 }
3129 }
3130
Richard Smith7525ff62013-05-09 07:14:00 +00003131 // During the construction of an object, it is not yet 'const'.
3132 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3133 // and this doesn't do quite the right thing for const subobjects of the
3134 // object under construction.
3135 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3136 BaseType = Info.Ctx.getCanonicalType(BaseType);
3137 BaseType.removeLocalConst();
3138 }
3139
Richard Smith6d4c6582013-11-05 22:18:15 +00003140 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003141 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003142 //
3143 // FIXME: Not all local state is mutable. Allow local constant subobjects
3144 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003145 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3146 Info.EvalStatus.HasSideEffects) ||
3147 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003148 return CompleteObject();
3149
3150 return CompleteObject(BaseVal, BaseType);
3151}
3152
Richard Smith243ef902013-05-05 23:31:59 +00003153/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3154/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3155/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003156///
3157/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003158/// \param Conv - The expression for which we are performing the conversion.
3159/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003160/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3161/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003162/// \param LVal - The glvalue on which we are attempting to perform this action.
3163/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003164static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003165 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003166 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003167 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003168 return false;
3169
Richard Smith3229b742013-05-05 21:17:10 +00003170 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003171 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003172 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003173 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3174 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3175 // initializer until now for such expressions. Such an expression can't be
3176 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003177 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003178 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003179 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003180 }
Richard Smith3229b742013-05-05 21:17:10 +00003181 APValue Lit;
3182 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3183 return false;
3184 CompleteObject LitObj(&Lit, Base->getType());
3185 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003186 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003187 // We represent a string literal array as an lvalue pointing at the
3188 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003189 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003190 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3191 CompleteObject StrObj(&Str, Base->getType());
3192 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003193 }
Richard Smith11562c52011-10-28 17:51:58 +00003194 }
3195
Richard Smith3229b742013-05-05 21:17:10 +00003196 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3197 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003198}
3199
3200/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003201static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003202 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003203 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003204 return false;
3205
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003206 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003207 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003208 return false;
3209 }
3210
Richard Smith3229b742013-05-05 21:17:10 +00003211 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3212 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00003213}
3214
Richard Smith243ef902013-05-05 23:31:59 +00003215static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3216 return T->isSignedIntegerType() &&
3217 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3218}
3219
3220namespace {
Richard Smith43e77732013-05-07 04:50:00 +00003221struct CompoundAssignSubobjectHandler {
3222 EvalInfo &Info;
3223 const Expr *E;
3224 QualType PromotedLHSType;
3225 BinaryOperatorKind Opcode;
3226 const APValue &RHS;
3227
3228 static const AccessKinds AccessKind = AK_Assign;
3229
3230 typedef bool result_type;
3231
3232 bool checkConst(QualType QT) {
3233 // Assigning to a const object has undefined behavior.
3234 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003235 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003236 return false;
3237 }
3238 return true;
3239 }
3240
3241 bool failed() { return false; }
3242 bool found(APValue &Subobj, QualType SubobjType) {
3243 switch (Subobj.getKind()) {
3244 case APValue::Int:
3245 return found(Subobj.getInt(), SubobjType);
3246 case APValue::Float:
3247 return found(Subobj.getFloat(), SubobjType);
3248 case APValue::ComplexInt:
3249 case APValue::ComplexFloat:
3250 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003251 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003252 return false;
3253 case APValue::LValue:
3254 return foundPointer(Subobj, SubobjType);
3255 default:
3256 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003257 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003258 return false;
3259 }
3260 }
3261 bool found(APSInt &Value, QualType SubobjType) {
3262 if (!checkConst(SubobjType))
3263 return false;
3264
3265 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3266 // We don't support compound assignment on integer-cast-to-pointer
3267 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003268 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003269 return false;
3270 }
3271
3272 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3273 SubobjType, Value);
3274 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3275 return false;
3276 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3277 return true;
3278 }
3279 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003280 return checkConst(SubobjType) &&
3281 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3282 Value) &&
3283 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3284 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003285 }
3286 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3287 if (!checkConst(SubobjType))
3288 return false;
3289
3290 QualType PointeeType;
3291 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3292 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003293
3294 if (PointeeType.isNull() || !RHS.isInt() ||
3295 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003296 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003297 return false;
3298 }
3299
Richard Smithd6cc1982017-01-31 02:23:02 +00003300 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003301 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003302 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003303
3304 LValue LVal;
3305 LVal.setFrom(Info.Ctx, Subobj);
3306 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3307 return false;
3308 LVal.moveInto(Subobj);
3309 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003310 }
3311 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3312 llvm_unreachable("shouldn't encounter string elements here");
3313 }
3314};
3315} // end anonymous namespace
3316
3317const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3318
3319/// Perform a compound assignment of LVal <op>= RVal.
3320static bool handleCompoundAssignment(
3321 EvalInfo &Info, const Expr *E,
3322 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3323 BinaryOperatorKind Opcode, const APValue &RVal) {
3324 if (LVal.Designator.Invalid)
3325 return false;
3326
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003327 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003328 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003329 return false;
3330 }
3331
3332 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3333 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3334 RVal };
3335 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3336}
3337
3338namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003339struct IncDecSubobjectHandler {
3340 EvalInfo &Info;
3341 const Expr *E;
3342 AccessKinds AccessKind;
3343 APValue *Old;
3344
3345 typedef bool result_type;
3346
3347 bool checkConst(QualType QT) {
3348 // Assigning to a const object has undefined behavior.
3349 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003350 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003351 return false;
3352 }
3353 return true;
3354 }
3355
3356 bool failed() { return false; }
3357 bool found(APValue &Subobj, QualType SubobjType) {
3358 // Stash the old value. Also clear Old, so we don't clobber it later
3359 // if we're post-incrementing a complex.
3360 if (Old) {
3361 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003362 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003363 }
3364
3365 switch (Subobj.getKind()) {
3366 case APValue::Int:
3367 return found(Subobj.getInt(), SubobjType);
3368 case APValue::Float:
3369 return found(Subobj.getFloat(), SubobjType);
3370 case APValue::ComplexInt:
3371 return found(Subobj.getComplexIntReal(),
3372 SubobjType->castAs<ComplexType>()->getElementType()
3373 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3374 case APValue::ComplexFloat:
3375 return found(Subobj.getComplexFloatReal(),
3376 SubobjType->castAs<ComplexType>()->getElementType()
3377 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3378 case APValue::LValue:
3379 return foundPointer(Subobj, SubobjType);
3380 default:
3381 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003382 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003383 return false;
3384 }
3385 }
3386 bool found(APSInt &Value, QualType SubobjType) {
3387 if (!checkConst(SubobjType))
3388 return false;
3389
3390 if (!SubobjType->isIntegerType()) {
3391 // We don't support increment / decrement on integer-cast-to-pointer
3392 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003393 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003394 return false;
3395 }
3396
3397 if (Old) *Old = APValue(Value);
3398
3399 // bool arithmetic promotes to int, and the conversion back to bool
3400 // doesn't reduce mod 2^n, so special-case it.
3401 if (SubobjType->isBooleanType()) {
3402 if (AccessKind == AK_Increment)
3403 Value = 1;
3404 else
3405 Value = !Value;
3406 return true;
3407 }
3408
3409 bool WasNegative = Value.isNegative();
3410 if (AccessKind == AK_Increment) {
3411 ++Value;
3412
3413 if (!WasNegative && Value.isNegative() &&
3414 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3415 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003416 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003417 }
3418 } else {
3419 --Value;
3420
3421 if (WasNegative && !Value.isNegative() &&
3422 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3423 unsigned BitWidth = Value.getBitWidth();
3424 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3425 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003426 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003427 }
3428 }
3429 return true;
3430 }
3431 bool found(APFloat &Value, QualType SubobjType) {
3432 if (!checkConst(SubobjType))
3433 return false;
3434
3435 if (Old) *Old = APValue(Value);
3436
3437 APFloat One(Value.getSemantics(), 1);
3438 if (AccessKind == AK_Increment)
3439 Value.add(One, APFloat::rmNearestTiesToEven);
3440 else
3441 Value.subtract(One, APFloat::rmNearestTiesToEven);
3442 return true;
3443 }
3444 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3445 if (!checkConst(SubobjType))
3446 return false;
3447
3448 QualType PointeeType;
3449 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3450 PointeeType = PT->getPointeeType();
3451 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003452 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003453 return false;
3454 }
3455
3456 LValue LVal;
3457 LVal.setFrom(Info.Ctx, Subobj);
3458 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3459 AccessKind == AK_Increment ? 1 : -1))
3460 return false;
3461 LVal.moveInto(Subobj);
3462 return true;
3463 }
3464 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3465 llvm_unreachable("shouldn't encounter string elements here");
3466 }
3467};
3468} // end anonymous namespace
3469
3470/// Perform an increment or decrement on LVal.
3471static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3472 QualType LValType, bool IsIncrement, APValue *Old) {
3473 if (LVal.Designator.Invalid)
3474 return false;
3475
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003476 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003477 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003478 return false;
3479 }
3480
3481 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3482 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3483 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3484 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3485}
3486
Richard Smithe97cbd72011-11-11 04:05:33 +00003487/// Build an lvalue for the object argument of a member function call.
3488static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3489 LValue &This) {
3490 if (Object->getType()->isPointerType())
3491 return EvaluatePointer(Object, This, Info);
3492
3493 if (Object->isGLValue())
3494 return EvaluateLValue(Object, This, Info);
3495
Richard Smithd9f663b2013-04-22 15:31:51 +00003496 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003497 return EvaluateTemporary(Object, This, Info);
3498
Faisal Valie690b7a2016-07-02 22:34:24 +00003499 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003500 return false;
3501}
3502
3503/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3504/// lvalue referring to the result.
3505///
3506/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003507/// \param LV - An lvalue referring to the base of the member pointer.
3508/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003509/// \param IncludeMember - Specifies whether the member itself is included in
3510/// the resulting LValue subobject designator. This is not possible when
3511/// creating a bound member function.
3512/// \return The field or method declaration to which the member pointer refers,
3513/// or 0 if evaluation fails.
3514static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003515 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003516 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003517 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003518 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003519 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003520 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003521 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003522
3523 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3524 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003525 if (!MemPtr.getDecl()) {
3526 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003527 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003528 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003529 }
Richard Smith253c2a32012-01-27 01:14:48 +00003530
Richard Smith027bf112011-11-17 22:56:20 +00003531 if (MemPtr.isDerivedMember()) {
3532 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003533 // The end of the derived-to-base path for the base object must match the
3534 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003535 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003536 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003537 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003538 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003539 }
Richard Smith027bf112011-11-17 22:56:20 +00003540 unsigned PathLengthToMember =
3541 LV.Designator.Entries.size() - MemPtr.Path.size();
3542 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3543 const CXXRecordDecl *LVDecl = getAsBaseClass(
3544 LV.Designator.Entries[PathLengthToMember + I]);
3545 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003546 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003547 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003548 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003549 }
Richard Smith027bf112011-11-17 22:56:20 +00003550 }
3551
3552 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003553 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003554 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003555 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003556 } else if (!MemPtr.Path.empty()) {
3557 // Extend the LValue path with the member pointer's path.
3558 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3559 MemPtr.Path.size() + IncludeMember);
3560
3561 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003562 if (const PointerType *PT = LVType->getAs<PointerType>())
3563 LVType = PT->getPointeeType();
3564 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3565 assert(RD && "member pointer access on non-class-type expression");
3566 // The first class in the path is that of the lvalue.
3567 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3568 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003569 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003570 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003571 RD = Base;
3572 }
3573 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003574 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3575 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003576 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003577 }
3578
3579 // Add the member. Note that we cannot build bound member functions here.
3580 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003581 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003582 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003583 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003584 } else if (const IndirectFieldDecl *IFD =
3585 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003586 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003587 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003588 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003589 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003590 }
Richard Smith027bf112011-11-17 22:56:20 +00003591 }
3592
3593 return MemPtr.getDecl();
3594}
3595
Richard Smith84401042013-06-03 05:03:02 +00003596static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3597 const BinaryOperator *BO,
3598 LValue &LV,
3599 bool IncludeMember = true) {
3600 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3601
3602 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003603 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003604 MemberPtr MemPtr;
3605 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3606 }
Craig Topper36250ad2014-05-12 05:36:57 +00003607 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003608 }
3609
3610 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3611 BO->getRHS(), IncludeMember);
3612}
3613
Richard Smith027bf112011-11-17 22:56:20 +00003614/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3615/// the provided lvalue, which currently refers to the base object.
3616static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3617 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003618 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003619 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003620 return false;
3621
Richard Smitha8105bc2012-01-06 16:39:00 +00003622 QualType TargetQT = E->getType();
3623 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3624 TargetQT = PT->getPointeeType();
3625
3626 // Check this cast lands within the final derived-to-base subobject path.
3627 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003628 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003629 << D.MostDerivedType << TargetQT;
3630 return false;
3631 }
3632
Richard Smith027bf112011-11-17 22:56:20 +00003633 // Check the type of the final cast. We don't need to check the path,
3634 // since a cast can only be formed if the path is unique.
3635 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003636 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3637 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003638 if (NewEntriesSize == D.MostDerivedPathLength)
3639 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3640 else
Richard Smith027bf112011-11-17 22:56:20 +00003641 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003642 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003643 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003644 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003645 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003646 }
Richard Smith027bf112011-11-17 22:56:20 +00003647
3648 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003649 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003650}
3651
Mike Stump876387b2009-10-27 22:09:17 +00003652namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003653enum EvalStmtResult {
3654 /// Evaluation failed.
3655 ESR_Failed,
3656 /// Hit a 'return' statement.
3657 ESR_Returned,
3658 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003659 ESR_Succeeded,
3660 /// Hit a 'continue' statement.
3661 ESR_Continue,
3662 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003663 ESR_Break,
3664 /// Still scanning for 'case' or 'default' statement.
3665 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003666};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003667}
Richard Smith254a73d2011-10-28 22:34:42 +00003668
Richard Smith97fcf4b2016-08-14 23:15:52 +00003669static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3670 // We don't need to evaluate the initializer for a static local.
3671 if (!VD->hasLocalStorage())
3672 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003673
Richard Smith97fcf4b2016-08-14 23:15:52 +00003674 LValue Result;
3675 Result.set(VD, Info.CurrentCall->Index);
3676 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003677
Richard Smith97fcf4b2016-08-14 23:15:52 +00003678 const Expr *InitE = VD->getInit();
3679 if (!InitE) {
3680 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3681 << false << VD->getType();
3682 Val = APValue();
3683 return false;
3684 }
Richard Smith51f03172013-06-20 03:00:05 +00003685
Richard Smith97fcf4b2016-08-14 23:15:52 +00003686 if (InitE->isValueDependent())
3687 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003688
Richard Smith97fcf4b2016-08-14 23:15:52 +00003689 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3690 // Wipe out any partially-computed value, to allow tracking that this
3691 // evaluation failed.
3692 Val = APValue();
3693 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003694 }
3695
3696 return true;
3697}
3698
Richard Smith97fcf4b2016-08-14 23:15:52 +00003699static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3700 bool OK = true;
3701
3702 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3703 OK &= EvaluateVarDecl(Info, VD);
3704
3705 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3706 for (auto *BD : DD->bindings())
3707 if (auto *VD = BD->getHoldingVar())
3708 OK &= EvaluateDecl(Info, VD);
3709
3710 return OK;
3711}
3712
3713
Richard Smith4e18ca52013-05-06 05:56:11 +00003714/// Evaluate a condition (either a variable declaration or an expression).
3715static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3716 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003717 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003718 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3719 return false;
3720 return EvaluateAsBooleanCondition(Cond, Result, Info);
3721}
3722
Richard Smith89210072016-04-04 23:29:43 +00003723namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003724/// \brief A location where the result (returned value) of evaluating a
3725/// statement should be stored.
3726struct StmtResult {
3727 /// The APValue that should be filled in with the returned value.
3728 APValue &Value;
3729 /// The location containing the result, if any (used to support RVO).
3730 const LValue *Slot;
3731};
Richard Smith89210072016-04-04 23:29:43 +00003732}
Richard Smith52a980a2015-08-28 02:43:42 +00003733
3734static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003735 const Stmt *S,
3736 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003737
3738/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003739static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003740 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003741 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003742 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003743 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003744 case ESR_Break:
3745 return ESR_Succeeded;
3746 case ESR_Succeeded:
3747 case ESR_Continue:
3748 return ESR_Continue;
3749 case ESR_Failed:
3750 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003751 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003752 return ESR;
3753 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003754 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003755}
3756
Richard Smith496ddcf2013-05-12 17:32:42 +00003757/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003758static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003759 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003760 BlockScopeRAII Scope(Info);
3761
Richard Smith496ddcf2013-05-12 17:32:42 +00003762 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003763 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003764 {
3765 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003766 if (const Stmt *Init = SS->getInit()) {
3767 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3768 if (ESR != ESR_Succeeded)
3769 return ESR;
3770 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003771 if (SS->getConditionVariable() &&
3772 !EvaluateDecl(Info, SS->getConditionVariable()))
3773 return ESR_Failed;
3774 if (!EvaluateInteger(SS->getCond(), Value, Info))
3775 return ESR_Failed;
3776 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003777
3778 // Find the switch case corresponding to the value of the condition.
3779 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003780 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003781 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3782 SC = SC->getNextSwitchCase()) {
3783 if (isa<DefaultStmt>(SC)) {
3784 Found = SC;
3785 continue;
3786 }
3787
3788 const CaseStmt *CS = cast<CaseStmt>(SC);
3789 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3790 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3791 : LHS;
3792 if (LHS <= Value && Value <= RHS) {
3793 Found = SC;
3794 break;
3795 }
3796 }
3797
3798 if (!Found)
3799 return ESR_Succeeded;
3800
3801 // Search the switch body for the switch case and evaluate it from there.
3802 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3803 case ESR_Break:
3804 return ESR_Succeeded;
3805 case ESR_Succeeded:
3806 case ESR_Continue:
3807 case ESR_Failed:
3808 case ESR_Returned:
3809 return ESR;
3810 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003811 // This can only happen if the switch case is nested within a statement
3812 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003813 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003814 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003815 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003816 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003817}
3818
Richard Smith254a73d2011-10-28 22:34:42 +00003819// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003820static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003821 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003822 if (!Info.nextStep(S))
3823 return ESR_Failed;
3824
Richard Smith496ddcf2013-05-12 17:32:42 +00003825 // If we're hunting down a 'case' or 'default' label, recurse through
3826 // substatements until we hit the label.
3827 if (Case) {
3828 // FIXME: We don't start the lifetime of objects whose initialization we
3829 // jump over. However, such objects must be of class type with a trivial
3830 // default constructor that initialize all subobjects, so must be empty,
3831 // so this almost never matters.
3832 switch (S->getStmtClass()) {
3833 case Stmt::CompoundStmtClass:
3834 // FIXME: Precompute which substatement of a compound statement we
3835 // would jump to, and go straight there rather than performing a
3836 // linear scan each time.
3837 case Stmt::LabelStmtClass:
3838 case Stmt::AttributedStmtClass:
3839 case Stmt::DoStmtClass:
3840 break;
3841
3842 case Stmt::CaseStmtClass:
3843 case Stmt::DefaultStmtClass:
3844 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003845 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003846 break;
3847
3848 case Stmt::IfStmtClass: {
3849 // FIXME: Precompute which side of an 'if' we would jump to, and go
3850 // straight there rather than scanning both sides.
3851 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003852
3853 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3854 // preceded by our switch label.
3855 BlockScopeRAII Scope(Info);
3856
Richard Smith496ddcf2013-05-12 17:32:42 +00003857 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3858 if (ESR != ESR_CaseNotFound || !IS->getElse())
3859 return ESR;
3860 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3861 }
3862
3863 case Stmt::WhileStmtClass: {
3864 EvalStmtResult ESR =
3865 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3866 if (ESR != ESR_Continue)
3867 return ESR;
3868 break;
3869 }
3870
3871 case Stmt::ForStmtClass: {
3872 const ForStmt *FS = cast<ForStmt>(S);
3873 EvalStmtResult ESR =
3874 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3875 if (ESR != ESR_Continue)
3876 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003877 if (FS->getInc()) {
3878 FullExpressionRAII IncScope(Info);
3879 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3880 return ESR_Failed;
3881 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003882 break;
3883 }
3884
3885 case Stmt::DeclStmtClass:
3886 // FIXME: If the variable has initialization that can't be jumped over,
3887 // bail out of any immediately-surrounding compound-statement too.
3888 default:
3889 return ESR_CaseNotFound;
3890 }
3891 }
3892
Richard Smith254a73d2011-10-28 22:34:42 +00003893 switch (S->getStmtClass()) {
3894 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003895 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003896 // Don't bother evaluating beyond an expression-statement which couldn't
3897 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003898 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003899 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003900 return ESR_Failed;
3901 return ESR_Succeeded;
3902 }
3903
Faisal Valie690b7a2016-07-02 22:34:24 +00003904 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003905 return ESR_Failed;
3906
3907 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003908 return ESR_Succeeded;
3909
Richard Smithd9f663b2013-04-22 15:31:51 +00003910 case Stmt::DeclStmtClass: {
3911 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003912 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003913 // Each declaration initialization is its own full-expression.
3914 // FIXME: This isn't quite right; if we're performing aggregate
3915 // initialization, each braced subexpression is its own full-expression.
3916 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003917 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003918 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003919 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003920 return ESR_Succeeded;
3921 }
3922
Richard Smith357362d2011-12-13 06:39:58 +00003923 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003924 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003925 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003926 if (RetExpr &&
3927 !(Result.Slot
3928 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3929 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003930 return ESR_Failed;
3931 return ESR_Returned;
3932 }
Richard Smith254a73d2011-10-28 22:34:42 +00003933
3934 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003935 BlockScopeRAII Scope(Info);
3936
Richard Smith254a73d2011-10-28 22:34:42 +00003937 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003938 for (const auto *BI : CS->body()) {
3939 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003940 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003941 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003942 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003943 return ESR;
3944 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003945 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003946 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003947
3948 case Stmt::IfStmtClass: {
3949 const IfStmt *IS = cast<IfStmt>(S);
3950
3951 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003952 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003953 if (const Stmt *Init = IS->getInit()) {
3954 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3955 if (ESR != ESR_Succeeded)
3956 return ESR;
3957 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003958 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003959 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003960 return ESR_Failed;
3961
3962 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3963 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3964 if (ESR != ESR_Succeeded)
3965 return ESR;
3966 }
3967 return ESR_Succeeded;
3968 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003969
3970 case Stmt::WhileStmtClass: {
3971 const WhileStmt *WS = cast<WhileStmt>(S);
3972 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003973 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003974 bool Continue;
3975 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3976 Continue))
3977 return ESR_Failed;
3978 if (!Continue)
3979 break;
3980
3981 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3982 if (ESR != ESR_Continue)
3983 return ESR;
3984 }
3985 return ESR_Succeeded;
3986 }
3987
3988 case Stmt::DoStmtClass: {
3989 const DoStmt *DS = cast<DoStmt>(S);
3990 bool Continue;
3991 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003992 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003993 if (ESR != ESR_Continue)
3994 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003995 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003996
Richard Smith08d6a2c2013-07-24 07:11:57 +00003997 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003998 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3999 return ESR_Failed;
4000 } while (Continue);
4001 return ESR_Succeeded;
4002 }
4003
4004 case Stmt::ForStmtClass: {
4005 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004006 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004007 if (FS->getInit()) {
4008 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4009 if (ESR != ESR_Succeeded)
4010 return ESR;
4011 }
4012 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004013 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004014 bool Continue = true;
4015 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4016 FS->getCond(), Continue))
4017 return ESR_Failed;
4018 if (!Continue)
4019 break;
4020
4021 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4022 if (ESR != ESR_Continue)
4023 return ESR;
4024
Richard Smith08d6a2c2013-07-24 07:11:57 +00004025 if (FS->getInc()) {
4026 FullExpressionRAII IncScope(Info);
4027 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4028 return ESR_Failed;
4029 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004030 }
4031 return ESR_Succeeded;
4032 }
4033
Richard Smith896e0d72013-05-06 06:51:17 +00004034 case Stmt::CXXForRangeStmtClass: {
4035 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004036 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004037
4038 // Initialize the __range variable.
4039 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4040 if (ESR != ESR_Succeeded)
4041 return ESR;
4042
4043 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004044 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4045 if (ESR != ESR_Succeeded)
4046 return ESR;
4047 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004048 if (ESR != ESR_Succeeded)
4049 return ESR;
4050
4051 while (true) {
4052 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004053 {
4054 bool Continue = true;
4055 FullExpressionRAII CondExpr(Info);
4056 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4057 return ESR_Failed;
4058 if (!Continue)
4059 break;
4060 }
Richard Smith896e0d72013-05-06 06:51:17 +00004061
4062 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004063 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004064 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4065 if (ESR != ESR_Succeeded)
4066 return ESR;
4067
4068 // Loop body.
4069 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4070 if (ESR != ESR_Continue)
4071 return ESR;
4072
4073 // Increment: ++__begin
4074 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4075 return ESR_Failed;
4076 }
4077
4078 return ESR_Succeeded;
4079 }
4080
Richard Smith496ddcf2013-05-12 17:32:42 +00004081 case Stmt::SwitchStmtClass:
4082 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4083
Richard Smith4e18ca52013-05-06 05:56:11 +00004084 case Stmt::ContinueStmtClass:
4085 return ESR_Continue;
4086
4087 case Stmt::BreakStmtClass:
4088 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004089
4090 case Stmt::LabelStmtClass:
4091 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4092
4093 case Stmt::AttributedStmtClass:
4094 // As a general principle, C++11 attributes can be ignored without
4095 // any semantic impact.
4096 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4097 Case);
4098
4099 case Stmt::CaseStmtClass:
4100 case Stmt::DefaultStmtClass:
4101 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004102 }
4103}
4104
Richard Smithcc36f692011-12-22 02:22:31 +00004105/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4106/// default constructor. If so, we'll fold it whether or not it's marked as
4107/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4108/// so we need special handling.
4109static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004110 const CXXConstructorDecl *CD,
4111 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004112 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4113 return false;
4114
Richard Smith66e05fe2012-01-18 05:21:49 +00004115 // Value-initialization does not call a trivial default constructor, so such a
4116 // call is a core constant expression whether or not the constructor is
4117 // constexpr.
4118 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004119 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004120 // FIXME: If DiagDecl is an implicitly-declared special member function,
4121 // we should be much more explicit about why it's not constexpr.
4122 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4123 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4124 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004125 } else {
4126 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4127 }
4128 }
4129 return true;
4130}
4131
Richard Smith357362d2011-12-13 06:39:58 +00004132/// CheckConstexprFunction - Check that a function can be called in a constant
4133/// expression.
4134static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4135 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004136 const FunctionDecl *Definition,
4137 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004138 // Potential constant expressions can contain calls to declared, but not yet
4139 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004140 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004141 Declaration->isConstexpr())
4142 return false;
4143
Richard Smith0838f3a2013-05-14 05:18:44 +00004144 // Bail out with no diagnostic if the function declaration itself is invalid.
4145 // We will have produced a relevant diagnostic while parsing it.
4146 if (Declaration->isInvalidDecl())
4147 return false;
4148
Richard Smith357362d2011-12-13 06:39:58 +00004149 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004150 if (Definition && Definition->isConstexpr() &&
4151 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004152 return true;
4153
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004154 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004155 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Daniel Jasperffdee092017-05-02 19:21:42 +00004156
Richard Smith5179eb72016-06-28 19:03:57 +00004157 // If this function is not constexpr because it is an inherited
4158 // non-constexpr constructor, diagnose that directly.
4159 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4160 if (CD && CD->isInheritingConstructor()) {
4161 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Daniel Jasperffdee092017-05-02 19:21:42 +00004162 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004163 DiagDecl = CD = Inherited;
4164 }
4165
4166 // FIXME: If DiagDecl is an implicitly-declared special member function
4167 // or an inheriting constructor, we should be much more explicit about why
4168 // it's not constexpr.
4169 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004170 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004171 << CD->getInheritedConstructor().getConstructor()->getParent();
4172 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004173 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004174 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004175 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4176 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004177 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004178 }
4179 return false;
4180}
4181
Richard Smithbe6dd812014-11-19 21:27:17 +00004182/// Determine if a class has any fields that might need to be copied by a
4183/// trivial copy or move operation.
4184static bool hasFields(const CXXRecordDecl *RD) {
4185 if (!RD || RD->isEmpty())
4186 return false;
4187 for (auto *FD : RD->fields()) {
4188 if (FD->isUnnamedBitfield())
4189 continue;
4190 return true;
4191 }
4192 for (auto &Base : RD->bases())
4193 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4194 return true;
4195 return false;
4196}
4197
Richard Smithd62306a2011-11-10 06:34:14 +00004198namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004199typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004200}
4201
4202/// EvaluateArgs - Evaluate the arguments to a function call.
4203static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4204 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004205 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004206 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004207 I != E; ++I) {
4208 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4209 // If we're checking for a potential constant expression, evaluate all
4210 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004211 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004212 return false;
4213 Success = false;
4214 }
4215 }
4216 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004217}
4218
Richard Smith254a73d2011-10-28 22:34:42 +00004219/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004220static bool HandleFunctionCall(SourceLocation CallLoc,
4221 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004222 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004223 EvalInfo &Info, APValue &Result,
4224 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004225 ArgVector ArgValues(Args.size());
4226 if (!EvaluateArgs(Args, ArgValues, Info))
4227 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004228
Richard Smith253c2a32012-01-27 01:14:48 +00004229 if (!Info.CheckCallLimit(CallLoc))
4230 return false;
4231
4232 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004233
4234 // For a trivial copy or move assignment, perform an APValue copy. This is
4235 // essential for unions, where the operations performed by the assignment
4236 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004237 //
4238 // Skip this for non-union classes with no fields; in that case, the defaulted
4239 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004240 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004241 if (MD && MD->isDefaulted() &&
4242 (MD->getParent()->isUnion() ||
4243 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004244 assert(This &&
4245 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4246 LValue RHS;
4247 RHS.setFrom(Info.Ctx, ArgValues[0]);
4248 APValue RHSValue;
4249 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4250 RHS, RHSValue))
4251 return false;
4252 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4253 RHSValue))
4254 return false;
4255 This->moveInto(Result);
4256 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004257 } else if (MD && isLambdaCallOperator(MD)) {
4258 // We're in a lambda; determine the lambda capture field maps.
4259 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4260 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004261 }
4262
Richard Smith52a980a2015-08-28 02:43:42 +00004263 StmtResult Ret = {Result, ResultSlot};
4264 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004265 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004266 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004267 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004268 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004269 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004270 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004271}
4272
Richard Smithd62306a2011-11-10 06:34:14 +00004273/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004274static bool HandleConstructorCall(const Expr *E, const LValue &This,
4275 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004276 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004277 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004278 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004279 if (!Info.CheckCallLimit(CallLoc))
4280 return false;
4281
Richard Smith3607ffe2012-02-13 03:54:03 +00004282 const CXXRecordDecl *RD = Definition->getParent();
4283 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004284 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004285 return false;
4286 }
4287
Richard Smith5179eb72016-06-28 19:03:57 +00004288 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004289
Richard Smith52a980a2015-08-28 02:43:42 +00004290 // FIXME: Creating an APValue just to hold a nonexistent return value is
4291 // wasteful.
4292 APValue RetVal;
4293 StmtResult Ret = {RetVal, nullptr};
4294
Richard Smith5179eb72016-06-28 19:03:57 +00004295 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004296 if (Definition->isDelegatingConstructor()) {
4297 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004298 {
4299 FullExpressionRAII InitScope(Info);
4300 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4301 return false;
4302 }
Richard Smith52a980a2015-08-28 02:43:42 +00004303 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004304 }
4305
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004306 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004307 // essential for unions (or classes with anonymous union members), where the
4308 // operations performed by the constructor cannot be represented by
4309 // ctor-initializers.
4310 //
4311 // Skip this for empty non-union classes; we should not perform an
4312 // lvalue-to-rvalue conversion on them because their copy constructor does not
4313 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004314 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004315 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004316 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004317 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004318 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004319 return handleLValueToRValueConversion(
4320 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4321 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004322 }
4323
4324 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004325 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004326 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004327 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004328
John McCalld7bca762012-05-01 00:38:49 +00004329 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004330 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4331
Richard Smith08d6a2c2013-07-24 07:11:57 +00004332 // A scope for temporaries lifetime-extended by reference members.
4333 BlockScopeRAII LifetimeExtendedScope(Info);
4334
Richard Smith253c2a32012-01-27 01:14:48 +00004335 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004336 unsigned BasesSeen = 0;
4337#ifndef NDEBUG
4338 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4339#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004340 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004341 LValue Subobject = This;
4342 APValue *Value = &Result;
4343
4344 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004345 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004346 if (I->isBaseInitializer()) {
4347 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004348#ifndef NDEBUG
4349 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004350 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004351 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4352 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4353 "base class initializers not in expected order");
4354 ++BaseIt;
4355#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004356 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004357 BaseType->getAsCXXRecordDecl(), &Layout))
4358 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004359 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004360 } else if ((FD = I->getMember())) {
4361 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004362 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004363 if (RD->isUnion()) {
4364 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004365 Value = &Result.getUnionValue();
4366 } else {
4367 Value = &Result.getStructField(FD->getFieldIndex());
4368 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004369 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004370 // Walk the indirect field decl's chain to find the object to initialize,
4371 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004372 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004373 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004374 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4375 // Switch the union field if it differs. This happens if we had
4376 // preceding zero-initialization, and we're now initializing a union
4377 // subobject other than the first.
4378 // FIXME: In this case, the values of the other subobjects are
4379 // specified, since zero-initialization sets all padding bits to zero.
4380 if (Value->isUninit() ||
4381 (Value->isUnion() && Value->getUnionField() != FD)) {
4382 if (CD->isUnion())
4383 *Value = APValue(FD);
4384 else
4385 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004386 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004387 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004388 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004389 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004390 if (CD->isUnion())
4391 Value = &Value->getUnionValue();
4392 else
4393 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004394 }
Richard Smithd62306a2011-11-10 06:34:14 +00004395 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004396 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004397 }
Richard Smith253c2a32012-01-27 01:14:48 +00004398
Richard Smith08d6a2c2013-07-24 07:11:57 +00004399 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004400 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4401 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004402 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004403 // If we're checking for a potential constant expression, evaluate all
4404 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004405 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004406 return false;
4407 Success = false;
4408 }
Richard Smithd62306a2011-11-10 06:34:14 +00004409 }
4410
Richard Smithd9f663b2013-04-22 15:31:51 +00004411 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004412 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004413}
4414
Richard Smith5179eb72016-06-28 19:03:57 +00004415static bool HandleConstructorCall(const Expr *E, const LValue &This,
4416 ArrayRef<const Expr*> Args,
4417 const CXXConstructorDecl *Definition,
4418 EvalInfo &Info, APValue &Result) {
4419 ArgVector ArgValues(Args.size());
4420 if (!EvaluateArgs(Args, ArgValues, Info))
4421 return false;
4422
4423 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4424 Info, Result);
4425}
4426
Eli Friedman9a156e52008-11-12 09:44:48 +00004427//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004428// Generic Evaluation
4429//===----------------------------------------------------------------------===//
4430namespace {
4431
Aaron Ballman68af21c2014-01-03 19:26:43 +00004432template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004433class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004434 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004435private:
Richard Smith52a980a2015-08-28 02:43:42 +00004436 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004437 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004438 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004439 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004440 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004441 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004442 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004443
Richard Smith17100ba2012-02-16 02:46:34 +00004444 // Check whether a conditional operator with a non-constant condition is a
4445 // potential constant expression. If neither arm is a potential constant
4446 // expression, then the conditional operator is not either.
4447 template<typename ConditionalOperator>
4448 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004449 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004450
4451 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004452 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004453 {
Richard Smith17100ba2012-02-16 02:46:34 +00004454 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004455 StmtVisitorTy::Visit(E->getFalseExpr());
4456 if (Diag.empty())
4457 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004458 }
Richard Smith17100ba2012-02-16 02:46:34 +00004459
George Burgess IV8c892b52016-05-25 22:31:54 +00004460 {
4461 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004462 Diag.clear();
4463 StmtVisitorTy::Visit(E->getTrueExpr());
4464 if (Diag.empty())
4465 return;
4466 }
4467
4468 Error(E, diag::note_constexpr_conditional_never_const);
4469 }
4470
4471
4472 template<typename ConditionalOperator>
4473 bool HandleConditionalOperator(const ConditionalOperator *E) {
4474 bool BoolResult;
4475 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004476 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004477 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004478 return false;
4479 }
4480 if (Info.noteFailure()) {
4481 StmtVisitorTy::Visit(E->getTrueExpr());
4482 StmtVisitorTy::Visit(E->getFalseExpr());
4483 }
Richard Smith17100ba2012-02-16 02:46:34 +00004484 return false;
4485 }
4486
4487 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4488 return StmtVisitorTy::Visit(EvalExpr);
4489 }
4490
Peter Collingbournee9200682011-05-13 03:29:01 +00004491protected:
4492 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004493 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004494 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4495
Richard Smith92b1ce02011-12-12 09:28:41 +00004496 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004497 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004498 }
4499
Aaron Ballman68af21c2014-01-03 19:26:43 +00004500 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004501
4502public:
4503 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4504
4505 EvalInfo &getEvalInfo() { return Info; }
4506
Richard Smithf57d8cb2011-12-09 22:58:01 +00004507 /// Report an evaluation error. This should only be called when an error is
4508 /// first discovered. When propagating an error, just return false.
4509 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004510 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004511 return false;
4512 }
4513 bool Error(const Expr *E) {
4514 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4515 }
4516
Aaron Ballman68af21c2014-01-03 19:26:43 +00004517 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004518 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004519 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004520 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004521 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004522 }
4523
Aaron Ballman68af21c2014-01-03 19:26:43 +00004524 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004525 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004526 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004527 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004528 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004529 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004530 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004531 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004532 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004533 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004534 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004535 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004536 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004537 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004538 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004539 // The initializer may not have been parsed yet, or might be erroneous.
4540 if (!E->getExpr())
4541 return Error(E);
4542 return StmtVisitorTy::Visit(E->getExpr());
4543 }
Richard Smith5894a912011-12-19 22:12:41 +00004544 // We cannot create any objects for which cleanups are required, so there is
4545 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004546 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004547 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004548
Aaron Ballman68af21c2014-01-03 19:26:43 +00004549 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004550 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4551 return static_cast<Derived*>(this)->VisitCastExpr(E);
4552 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004553 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004554 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4555 return static_cast<Derived*>(this)->VisitCastExpr(E);
4556 }
4557
Aaron Ballman68af21c2014-01-03 19:26:43 +00004558 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004559 switch (E->getOpcode()) {
4560 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004561 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004562
4563 case BO_Comma:
4564 VisitIgnoredValue(E->getLHS());
4565 return StmtVisitorTy::Visit(E->getRHS());
4566
4567 case BO_PtrMemD:
4568 case BO_PtrMemI: {
4569 LValue Obj;
4570 if (!HandleMemberPointerAccess(Info, E, Obj))
4571 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004572 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004573 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004574 return false;
4575 return DerivedSuccess(Result, E);
4576 }
4577 }
4578 }
4579
Aaron Ballman68af21c2014-01-03 19:26:43 +00004580 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004581 // Evaluate and cache the common expression. We treat it as a temporary,
4582 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004583 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004584 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004585 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004586
Richard Smith17100ba2012-02-16 02:46:34 +00004587 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004588 }
4589
Aaron Ballman68af21c2014-01-03 19:26:43 +00004590 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004591 bool IsBcpCall = false;
4592 // If the condition (ignoring parens) is a __builtin_constant_p call,
4593 // the result is a constant expression if it can be folded without
4594 // side-effects. This is an important GNU extension. See GCC PR38377
4595 // for discussion.
4596 if (const CallExpr *CallCE =
4597 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004598 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004599 IsBcpCall = true;
4600
4601 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4602 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004603 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004604 return false;
4605
Richard Smith6d4c6582013-11-05 22:18:15 +00004606 FoldConstant Fold(Info, IsBcpCall);
4607 if (!HandleConditionalOperator(E)) {
4608 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004609 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004610 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004611
4612 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004613 }
4614
Aaron Ballman68af21c2014-01-03 19:26:43 +00004615 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004616 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4617 return DerivedSuccess(*Value, E);
4618
4619 const Expr *Source = E->getSourceExpr();
4620 if (!Source)
4621 return Error(E);
4622 if (Source == E) { // sanity checking.
4623 assert(0 && "OpaqueValueExpr recursively refers to itself");
4624 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004625 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004626 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004627 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004628
Aaron Ballman68af21c2014-01-03 19:26:43 +00004629 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004630 APValue Result;
4631 if (!handleCallExpr(E, Result, nullptr))
4632 return false;
4633 return DerivedSuccess(Result, E);
4634 }
4635
4636 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004637 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004638 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004639 QualType CalleeType = Callee->getType();
4640
Craig Topper36250ad2014-05-12 05:36:57 +00004641 const FunctionDecl *FD = nullptr;
4642 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004643 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004644 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004645
Richard Smithe97cbd72011-11-11 04:05:33 +00004646 // Extract function decl and 'this' pointer from the callee.
4647 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004648 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004649 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4650 // Explicit bound member calls, such as x.f() or p->g();
4651 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004652 return false;
4653 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004654 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004655 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004656 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4657 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004658 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4659 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004660 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004661 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004662 return Error(Callee);
4663
4664 FD = dyn_cast<FunctionDecl>(Member);
4665 if (!FD)
4666 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004667 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004668 LValue Call;
4669 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004670 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004671
Richard Smitha8105bc2012-01-06 16:39:00 +00004672 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004673 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004674 FD = dyn_cast_or_null<FunctionDecl>(
4675 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004676 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004677 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004678 // Don't call function pointers which have been cast to some other type.
4679 // Per DR (no number yet), the caller and callee can differ in noexcept.
4680 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4681 CalleeType->getPointeeType(), FD->getType())) {
4682 return Error(E);
4683 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004684
4685 // Overloaded operator calls to member functions are represented as normal
4686 // calls with '*this' as the first argument.
4687 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4688 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004689 // FIXME: When selecting an implicit conversion for an overloaded
4690 // operator delete, we sometimes try to evaluate calls to conversion
4691 // operators without a 'this' parameter!
4692 if (Args.empty())
4693 return Error(E);
4694
Nick Lewycky13073a62017-06-12 21:15:44 +00004695 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004696 return false;
4697 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004698 Args = Args.slice(1);
Daniel Jasperffdee092017-05-02 19:21:42 +00004699 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004700 // Map the static invoker for the lambda back to the call operator.
4701 // Conveniently, we don't have to slice out the 'this' argument (as is
4702 // being done for the non-static case), since a static member function
4703 // doesn't have an implicit argument passed in.
4704 const CXXRecordDecl *ClosureClass = MD->getParent();
4705 assert(
4706 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4707 "Number of captures must be zero for conversion to function-ptr");
4708
4709 const CXXMethodDecl *LambdaCallOp =
4710 ClosureClass->getLambdaCallOperator();
4711
4712 // Set 'FD', the function that will be called below, to the call
4713 // operator. If the closure object represents a generic lambda, find
4714 // the corresponding specialization of the call operator.
4715
4716 if (ClosureClass->isGenericLambda()) {
4717 assert(MD->isFunctionTemplateSpecialization() &&
4718 "A generic lambda's static-invoker function must be a "
4719 "template specialization");
4720 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4721 FunctionTemplateDecl *CallOpTemplate =
4722 LambdaCallOp->getDescribedFunctionTemplate();
4723 void *InsertPos = nullptr;
4724 FunctionDecl *CorrespondingCallOpSpecialization =
4725 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4726 assert(CorrespondingCallOpSpecialization &&
4727 "We must always have a function call operator specialization "
4728 "that corresponds to our static invoker specialization");
4729 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4730 } else
4731 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004732 }
4733
Daniel Jasperffdee092017-05-02 19:21:42 +00004734
Richard Smithe97cbd72011-11-11 04:05:33 +00004735 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004736 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004737
Richard Smith47b34932012-02-01 02:39:43 +00004738 if (This && !This->checkSubobject(Info, E, CSK_This))
4739 return false;
4740
Richard Smith3607ffe2012-02-13 03:54:03 +00004741 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4742 // calls to such functions in constant expressions.
4743 if (This && !HasQualifier &&
4744 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4745 return Error(E, diag::note_constexpr_virtual_call);
4746
Craig Topper36250ad2014-05-12 05:36:57 +00004747 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004748 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004749
Nick Lewycky13073a62017-06-12 21:15:44 +00004750 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4751 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004752 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004753 return false;
4754
Richard Smith52a980a2015-08-28 02:43:42 +00004755 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004756 }
4757
Aaron Ballman68af21c2014-01-03 19:26:43 +00004758 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004759 return StmtVisitorTy::Visit(E->getInitializer());
4760 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004761 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004762 if (E->getNumInits() == 0)
4763 return DerivedZeroInitialization(E);
4764 if (E->getNumInits() == 1)
4765 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004766 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004767 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004768 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004769 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004770 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004771 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004772 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004773 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004774 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004775 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004776 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004777
Richard Smithd62306a2011-11-10 06:34:14 +00004778 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004779 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004780 assert(!E->isArrow() && "missing call to bound member function?");
4781
Richard Smith2e312c82012-03-03 22:46:17 +00004782 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004783 if (!Evaluate(Val, Info, E->getBase()))
4784 return false;
4785
4786 QualType BaseTy = E->getBase()->getType();
4787
4788 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004789 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004790 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004791 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004792 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4793
Richard Smith3229b742013-05-05 21:17:10 +00004794 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004795 SubobjectDesignator Designator(BaseTy);
4796 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004797
Richard Smith3229b742013-05-05 21:17:10 +00004798 APValue Result;
4799 return extractSubobject(Info, E, Obj, Designator, Result) &&
4800 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004801 }
4802
Aaron Ballman68af21c2014-01-03 19:26:43 +00004803 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004804 switch (E->getCastKind()) {
4805 default:
4806 break;
4807
Richard Smitha23ab512013-05-23 00:30:41 +00004808 case CK_AtomicToNonAtomic: {
4809 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004810 // This does not need to be done in place even for class/array types:
4811 // atomic-to-non-atomic conversion implies copying the object
4812 // representation.
4813 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004814 return false;
4815 return DerivedSuccess(AtomicVal, E);
4816 }
4817
Richard Smith11562c52011-10-28 17:51:58 +00004818 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004819 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004820 return StmtVisitorTy::Visit(E->getSubExpr());
4821
4822 case CK_LValueToRValue: {
4823 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004824 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4825 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004826 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004827 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004828 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004829 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004830 return false;
4831 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004832 }
4833 }
4834
Richard Smithf57d8cb2011-12-09 22:58:01 +00004835 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004836 }
4837
Aaron Ballman68af21c2014-01-03 19:26:43 +00004838 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004839 return VisitUnaryPostIncDec(UO);
4840 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004841 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004842 return VisitUnaryPostIncDec(UO);
4843 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004844 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004845 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004846 return Error(UO);
4847
4848 LValue LVal;
4849 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4850 return false;
4851 APValue RVal;
4852 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4853 UO->isIncrementOp(), &RVal))
4854 return false;
4855 return DerivedSuccess(RVal, UO);
4856 }
4857
Aaron Ballman68af21c2014-01-03 19:26:43 +00004858 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004859 // We will have checked the full-expressions inside the statement expression
4860 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004861 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004862 return Error(E);
4863
Richard Smith08d6a2c2013-07-24 07:11:57 +00004864 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004865 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004866 if (CS->body_empty())
4867 return true;
4868
Richard Smith51f03172013-06-20 03:00:05 +00004869 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4870 BE = CS->body_end();
4871 /**/; ++BI) {
4872 if (BI + 1 == BE) {
4873 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4874 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004875 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004876 diag::note_constexpr_stmt_expr_unsupported);
4877 return false;
4878 }
4879 return this->Visit(FinalExpr);
4880 }
4881
4882 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004883 StmtResult Result = { ReturnValue, nullptr };
4884 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004885 if (ESR != ESR_Succeeded) {
4886 // FIXME: If the statement-expression terminated due to 'return',
4887 // 'break', or 'continue', it would be nice to propagate that to
4888 // the outer statement evaluation rather than bailing out.
4889 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004890 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004891 diag::note_constexpr_stmt_expr_unsupported);
4892 return false;
4893 }
4894 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004895
4896 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004897 }
4898
Richard Smith4a678122011-10-24 18:44:57 +00004899 /// Visit a value which is evaluated, but whose value is ignored.
4900 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004901 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004902 }
David Majnemere9807b22016-02-26 04:23:19 +00004903
4904 /// Potentially visit a MemberExpr's base expression.
4905 void VisitIgnoredBaseExpression(const Expr *E) {
4906 // While MSVC doesn't evaluate the base expression, it does diagnose the
4907 // presence of side-effecting behavior.
4908 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4909 return;
4910 VisitIgnoredValue(E);
4911 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004912};
4913
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004914}
Peter Collingbournee9200682011-05-13 03:29:01 +00004915
4916//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004917// Common base class for lvalue and temporary evaluation.
4918//===----------------------------------------------------------------------===//
4919namespace {
4920template<class Derived>
4921class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004922 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004923protected:
4924 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00004925 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00004926 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004927 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004928
4929 bool Success(APValue::LValueBase B) {
4930 Result.set(B);
4931 return true;
4932 }
4933
George Burgess IVf9013bf2017-02-10 22:52:29 +00004934 bool evaluatePointer(const Expr *E, LValue &Result) {
4935 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4936 }
4937
Richard Smith027bf112011-11-17 22:56:20 +00004938public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004939 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4940 : ExprEvaluatorBaseTy(Info), Result(Result),
4941 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00004942
Richard Smith2e312c82012-03-03 22:46:17 +00004943 bool Success(const APValue &V, const Expr *E) {
4944 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004945 return true;
4946 }
Richard Smith027bf112011-11-17 22:56:20 +00004947
Richard Smith027bf112011-11-17 22:56:20 +00004948 bool VisitMemberExpr(const MemberExpr *E) {
4949 // Handle non-static data members.
4950 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004951 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004952 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004953 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00004954 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004955 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004956 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004957 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004958 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004959 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004960 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004961 BaseTy = E->getBase()->getType();
4962 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004963 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004964 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004965 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004966 Result.setInvalid(E);
4967 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004968 }
Richard Smith027bf112011-11-17 22:56:20 +00004969
Richard Smith1b78b3d2012-01-25 22:15:11 +00004970 const ValueDecl *MD = E->getMemberDecl();
4971 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4972 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4973 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4974 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004975 if (!HandleLValueMember(this->Info, E, Result, FD))
4976 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004977 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004978 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4979 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004980 } else
4981 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004982
Richard Smith1b78b3d2012-01-25 22:15:11 +00004983 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004984 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004985 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004986 RefValue))
4987 return false;
4988 return Success(RefValue, E);
4989 }
4990 return true;
4991 }
4992
4993 bool VisitBinaryOperator(const BinaryOperator *E) {
4994 switch (E->getOpcode()) {
4995 default:
4996 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4997
4998 case BO_PtrMemD:
4999 case BO_PtrMemI:
5000 return HandleMemberPointerAccess(this->Info, E, Result);
5001 }
5002 }
5003
5004 bool VisitCastExpr(const CastExpr *E) {
5005 switch (E->getCastKind()) {
5006 default:
5007 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5008
5009 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005010 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005011 if (!this->Visit(E->getSubExpr()))
5012 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005013
5014 // Now figure out the necessary offset to add to the base LV to get from
5015 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005016 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5017 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005018 }
5019 }
5020};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005021}
Richard Smith027bf112011-11-17 22:56:20 +00005022
5023//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005024// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005025//
5026// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5027// function designators (in C), decl references to void objects (in C), and
5028// temporaries (if building with -Wno-address-of-temporary).
5029//
5030// LValue evaluation produces values comprising a base expression of one of the
5031// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005032// - Declarations
5033// * VarDecl
5034// * FunctionDecl
5035// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005036// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005037// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005038// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005039// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005040// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005041// * ObjCEncodeExpr
5042// * AddrLabelExpr
5043// * BlockExpr
5044// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005045// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005046// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005047// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005048// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5049// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005050// * A MaterializeTemporaryExpr that has static storage duration, with no
5051// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005052// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005053//===----------------------------------------------------------------------===//
5054namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005055class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005056 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005057public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005058 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5059 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005060
Richard Smith11562c52011-10-28 17:51:58 +00005061 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005062 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005063
Peter Collingbournee9200682011-05-13 03:29:01 +00005064 bool VisitDeclRefExpr(const DeclRefExpr *E);
5065 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005066 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005067 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5068 bool VisitMemberExpr(const MemberExpr *E);
5069 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5070 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005071 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005072 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005073 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5074 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005075 bool VisitUnaryReal(const UnaryOperator *E);
5076 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005077 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5078 return VisitUnaryPreIncDec(UO);
5079 }
5080 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5081 return VisitUnaryPreIncDec(UO);
5082 }
Richard Smith3229b742013-05-05 21:17:10 +00005083 bool VisitBinAssign(const BinaryOperator *BO);
5084 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005085
Peter Collingbournee9200682011-05-13 03:29:01 +00005086 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005087 switch (E->getCastKind()) {
5088 default:
Richard Smith027bf112011-11-17 22:56:20 +00005089 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005090
Eli Friedmance3e02a2011-10-11 00:13:24 +00005091 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005092 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005093 if (!Visit(E->getSubExpr()))
5094 return false;
5095 Result.Designator.setInvalid();
5096 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005097
Richard Smith027bf112011-11-17 22:56:20 +00005098 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005099 if (!Visit(E->getSubExpr()))
5100 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005101 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005102 }
5103 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005104};
5105} // end anonymous namespace
5106
Richard Smith11562c52011-10-28 17:51:58 +00005107/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005108/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005109/// * function designators in C, and
5110/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005111/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005112static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5113 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005114 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005115 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005116 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005117}
5118
Peter Collingbournee9200682011-05-13 03:29:01 +00005119bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005120 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005121 return Success(FD);
5122 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005123 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005124 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005125 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005126 return Error(E);
5127}
Richard Smith733237d2011-10-24 23:14:33 +00005128
Faisal Vali0528a312016-11-13 06:09:16 +00005129
Richard Smith11562c52011-10-28 17:51:58 +00005130bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005131
5132 // If we are within a lambda's call operator, check whether the 'VD' referred
5133 // to within 'E' actually represents a lambda-capture that maps to a
5134 // data-member/field within the closure object, and if so, evaluate to the
5135 // field or what the field refers to.
5136 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5137 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5138 if (Info.checkingPotentialConstantExpression())
5139 return false;
5140 // Start with 'Result' referring to the complete closure object...
5141 Result = *Info.CurrentCall->This;
5142 // ... then update it to refer to the field of the closure object
5143 // that represents the capture.
5144 if (!HandleLValueMember(Info, E, Result, FD))
5145 return false;
5146 // And if the field is of reference type, update 'Result' to refer to what
5147 // the field refers to.
5148 if (FD->getType()->isReferenceType()) {
5149 APValue RVal;
5150 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5151 RVal))
5152 return false;
5153 Result.setFrom(Info.Ctx, RVal);
5154 }
5155 return true;
5156 }
5157 }
Craig Topper36250ad2014-05-12 05:36:57 +00005158 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005159 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5160 // Only if a local variable was declared in the function currently being
5161 // evaluated, do we expect to be able to find its value in the current
5162 // frame. (Otherwise it was likely declared in an enclosing context and
5163 // could either have a valid evaluatable value (for e.g. a constexpr
5164 // variable) or be ill-formed (and trigger an appropriate evaluation
5165 // diagnostic)).
5166 if (Info.CurrentCall->Callee &&
5167 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5168 Frame = Info.CurrentCall;
5169 }
5170 }
Richard Smith3229b742013-05-05 21:17:10 +00005171
Richard Smithfec09922011-11-01 16:57:24 +00005172 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005173 if (Frame) {
5174 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005175 return true;
5176 }
Richard Smithce40ad62011-11-12 22:28:03 +00005177 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005178 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005179
Richard Smith3229b742013-05-05 21:17:10 +00005180 APValue *V;
5181 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005182 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005183 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005184 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005185 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005186 return false;
5187 }
Richard Smith3229b742013-05-05 21:17:10 +00005188 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005189}
5190
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005191bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5192 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005193 // Walk through the expression to find the materialized temporary itself.
5194 SmallVector<const Expr *, 2> CommaLHSs;
5195 SmallVector<SubobjectAdjustment, 2> Adjustments;
5196 const Expr *Inner = E->GetTemporaryExpr()->
5197 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005198
Richard Smith84401042013-06-03 05:03:02 +00005199 // If we passed any comma operators, evaluate their LHSs.
5200 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5201 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5202 return false;
5203
Richard Smithe6c01442013-06-05 00:46:14 +00005204 // A materialized temporary with static storage duration can appear within the
5205 // result of a constant expression evaluation, so we need to preserve its
5206 // value for use outside this evaluation.
5207 APValue *Value;
5208 if (E->getStorageDuration() == SD_Static) {
5209 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005210 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005211 Result.set(E);
5212 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005213 Value = &Info.CurrentCall->
5214 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005215 Result.set(E, Info.CurrentCall->Index);
5216 }
5217
Richard Smithea4ad5d2013-06-06 08:19:16 +00005218 QualType Type = Inner->getType();
5219
Richard Smith84401042013-06-03 05:03:02 +00005220 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005221 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5222 (E->getStorageDuration() == SD_Static &&
5223 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5224 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005225 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005226 }
Richard Smith84401042013-06-03 05:03:02 +00005227
5228 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005229 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5230 --I;
5231 switch (Adjustments[I].Kind) {
5232 case SubobjectAdjustment::DerivedToBaseAdjustment:
5233 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5234 Type, Result))
5235 return false;
5236 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5237 break;
5238
5239 case SubobjectAdjustment::FieldAdjustment:
5240 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5241 return false;
5242 Type = Adjustments[I].Field->getType();
5243 break;
5244
5245 case SubobjectAdjustment::MemberPointerAdjustment:
5246 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5247 Adjustments[I].Ptr.RHS))
5248 return false;
5249 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5250 break;
5251 }
5252 }
5253
5254 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005255}
5256
Peter Collingbournee9200682011-05-13 03:29:01 +00005257bool
5258LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005259 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5260 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005261 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5262 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005263 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005264}
5265
Richard Smith6e525142011-12-27 12:18:28 +00005266bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005267 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005268 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005269
Faisal Valie690b7a2016-07-02 22:34:24 +00005270 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005271 << E->getExprOperand()->getType()
5272 << E->getExprOperand()->getSourceRange();
5273 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005274}
5275
Francois Pichet0066db92012-04-16 04:08:35 +00005276bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5277 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005278}
Francois Pichet0066db92012-04-16 04:08:35 +00005279
Peter Collingbournee9200682011-05-13 03:29:01 +00005280bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005281 // Handle static data members.
5282 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005283 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005284 return VisitVarDecl(E, VD);
5285 }
5286
Richard Smith254a73d2011-10-28 22:34:42 +00005287 // Handle static member functions.
5288 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5289 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005290 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005291 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005292 }
5293 }
5294
Richard Smithd62306a2011-11-10 06:34:14 +00005295 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005296 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005297}
5298
Peter Collingbournee9200682011-05-13 03:29:01 +00005299bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005300 // FIXME: Deal with vectors as array subscript bases.
5301 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005302 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005303
Nick Lewyckyad888682017-04-27 07:27:36 +00005304 bool Success = true;
5305 if (!evaluatePointer(E->getBase(), Result)) {
5306 if (!Info.noteFailure())
5307 return false;
5308 Success = false;
5309 }
Mike Stump11289f42009-09-09 15:08:12 +00005310
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005311 APSInt Index;
5312 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005313 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005314
Nick Lewyckyad888682017-04-27 07:27:36 +00005315 return Success &&
5316 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005317}
Eli Friedman9a156e52008-11-12 09:44:48 +00005318
Peter Collingbournee9200682011-05-13 03:29:01 +00005319bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005320 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005321}
5322
Richard Smith66c96992012-02-18 22:04:06 +00005323bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5324 if (!Visit(E->getSubExpr()))
5325 return false;
5326 // __real is a no-op on scalar lvalues.
5327 if (E->getSubExpr()->getType()->isAnyComplexType())
5328 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5329 return true;
5330}
5331
5332bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5333 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5334 "lvalue __imag__ on scalar?");
5335 if (!Visit(E->getSubExpr()))
5336 return false;
5337 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5338 return true;
5339}
5340
Richard Smith243ef902013-05-05 23:31:59 +00005341bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005342 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005343 return Error(UO);
5344
5345 if (!this->Visit(UO->getSubExpr()))
5346 return false;
5347
Richard Smith243ef902013-05-05 23:31:59 +00005348 return handleIncDec(
5349 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005350 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005351}
5352
5353bool LValueExprEvaluator::VisitCompoundAssignOperator(
5354 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005355 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005356 return Error(CAO);
5357
Richard Smith3229b742013-05-05 21:17:10 +00005358 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005359
5360 // The overall lvalue result is the result of evaluating the LHS.
5361 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005362 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005363 Evaluate(RHS, this->Info, CAO->getRHS());
5364 return false;
5365 }
5366
Richard Smith3229b742013-05-05 21:17:10 +00005367 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5368 return false;
5369
Richard Smith43e77732013-05-07 04:50:00 +00005370 return handleCompoundAssignment(
5371 this->Info, CAO,
5372 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5373 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005374}
5375
5376bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005377 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005378 return Error(E);
5379
Richard Smith3229b742013-05-05 21:17:10 +00005380 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005381
5382 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005383 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005384 Evaluate(NewVal, this->Info, E->getRHS());
5385 return false;
5386 }
5387
Richard Smith3229b742013-05-05 21:17:10 +00005388 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5389 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005390
5391 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005392 NewVal);
5393}
5394
Eli Friedman9a156e52008-11-12 09:44:48 +00005395//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005396// Pointer Evaluation
5397//===----------------------------------------------------------------------===//
5398
George Burgess IVe3763372016-12-22 02:50:20 +00005399/// \brief Attempts to compute the number of bytes available at the pointer
5400/// returned by a function with the alloc_size attribute. Returns true if we
5401/// were successful. Places an unsigned number into `Result`.
5402///
5403/// This expects the given CallExpr to be a call to a function with an
5404/// alloc_size attribute.
5405static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5406 const CallExpr *Call,
5407 llvm::APInt &Result) {
5408 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5409
5410 // alloc_size args are 1-indexed, 0 means not present.
5411 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5412 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5413 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5414 if (Call->getNumArgs() <= SizeArgNo)
5415 return false;
5416
5417 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5418 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5419 return false;
5420 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5421 return false;
5422 Into = Into.zextOrSelf(BitsInSizeT);
5423 return true;
5424 };
5425
5426 APSInt SizeOfElem;
5427 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5428 return false;
5429
5430 if (!AllocSize->getNumElemsParam()) {
5431 Result = std::move(SizeOfElem);
5432 return true;
5433 }
5434
5435 APSInt NumberOfElems;
5436 // Argument numbers start at 1
5437 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5438 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5439 return false;
5440
5441 bool Overflow;
5442 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5443 if (Overflow)
5444 return false;
5445
5446 Result = std::move(BytesAvailable);
5447 return true;
5448}
5449
5450/// \brief Convenience function. LVal's base must be a call to an alloc_size
5451/// function.
5452static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5453 const LValue &LVal,
5454 llvm::APInt &Result) {
5455 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5456 "Can't get the size of a non alloc_size function");
5457 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5458 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5459 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5460}
5461
5462/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5463/// a function with the alloc_size attribute. If it was possible to do so, this
5464/// function will return true, make Result's Base point to said function call,
5465/// and mark Result's Base as invalid.
5466static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5467 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005468 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005469 return false;
5470
5471 // Because we do no form of static analysis, we only support const variables.
5472 //
5473 // Additionally, we can't support parameters, nor can we support static
5474 // variables (in the latter case, use-before-assign isn't UB; in the former,
5475 // we have no clue what they'll be assigned to).
5476 const auto *VD =
5477 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5478 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5479 return false;
5480
5481 const Expr *Init = VD->getAnyInitializer();
5482 if (!Init)
5483 return false;
5484
5485 const Expr *E = Init->IgnoreParens();
5486 if (!tryUnwrapAllocSizeCall(E))
5487 return false;
5488
5489 // Store E instead of E unwrapped so that the type of the LValue's base is
5490 // what the user wanted.
5491 Result.setInvalid(E);
5492
5493 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith2cd56042017-08-29 01:52:13 +00005494 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005495 return true;
5496}
5497
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005498namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005499class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005500 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005501 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005502 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005503
Peter Collingbournee9200682011-05-13 03:29:01 +00005504 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005505 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005506 return true;
5507 }
George Burgess IVe3763372016-12-22 02:50:20 +00005508
George Burgess IVf9013bf2017-02-10 22:52:29 +00005509 bool evaluateLValue(const Expr *E, LValue &Result) {
5510 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5511 }
5512
5513 bool evaluatePointer(const Expr *E, LValue &Result) {
5514 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5515 }
5516
George Burgess IVe3763372016-12-22 02:50:20 +00005517 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005518public:
Mike Stump11289f42009-09-09 15:08:12 +00005519
George Burgess IVf9013bf2017-02-10 22:52:29 +00005520 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5521 : ExprEvaluatorBaseTy(info), Result(Result),
5522 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005523
Richard Smith2e312c82012-03-03 22:46:17 +00005524 bool Success(const APValue &V, const Expr *E) {
5525 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005526 return true;
5527 }
Richard Smithfddd3842011-12-30 21:15:51 +00005528 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005529 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5530 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005531 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005532 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005533
John McCall45d55e42010-05-07 21:00:08 +00005534 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005535 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005536 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005537 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005538 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005539 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5540 if (Info.noteFailure())
5541 EvaluateIgnoredValue(Info, E->getSubExpr());
5542 return Error(E);
5543 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005544 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005545 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005546 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005547 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005548 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005549 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005550 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005551 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005552 }
Richard Smithd62306a2011-11-10 06:34:14 +00005553 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005554 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005555 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005556 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005557 if (!Info.CurrentCall->This) {
5558 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005559 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005560 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005561 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005562 return false;
5563 }
Richard Smithd62306a2011-11-10 06:34:14 +00005564 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005565 // If we are inside a lambda's call operator, the 'this' expression refers
5566 // to the enclosing '*this' object (either by value or reference) which is
5567 // either copied into the closure object's field that represents the '*this'
5568 // or refers to '*this'.
5569 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5570 // Update 'Result' to refer to the data member/field of the closure object
5571 // that represents the '*this' capture.
5572 if (!HandleLValueMember(Info, E, Result,
Daniel Jasperffdee092017-05-02 19:21:42 +00005573 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005574 return false;
5575 // If we captured '*this' by reference, replace the field with its referent.
5576 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5577 ->isPointerType()) {
5578 APValue RVal;
5579 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5580 RVal))
5581 return false;
5582
5583 Result.setFrom(Info.Ctx, RVal);
5584 }
5585 }
Richard Smithd62306a2011-11-10 06:34:14 +00005586 return true;
5587 }
John McCallc07a0c72011-02-17 10:25:35 +00005588
Eli Friedman449fe542009-03-23 04:56:01 +00005589 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005590};
Chris Lattner05706e882008-07-11 18:11:29 +00005591} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005592
George Burgess IVf9013bf2017-02-10 22:52:29 +00005593static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5594 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005595 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005596 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005597}
5598
John McCall45d55e42010-05-07 21:00:08 +00005599bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005600 if (E->getOpcode() != BO_Add &&
5601 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005602 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005603
Chris Lattner05706e882008-07-11 18:11:29 +00005604 const Expr *PExp = E->getLHS();
5605 const Expr *IExp = E->getRHS();
5606 if (IExp->getType()->isPointerType())
5607 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005608
George Burgess IVf9013bf2017-02-10 22:52:29 +00005609 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005610 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005611 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005612
John McCall45d55e42010-05-07 21:00:08 +00005613 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005614 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005615 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005616
Richard Smith96e0c102011-11-04 02:25:55 +00005617 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005618 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005619
Ted Kremenek28831752012-08-23 20:46:57 +00005620 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005621 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005622}
Eli Friedman9a156e52008-11-12 09:44:48 +00005623
John McCall45d55e42010-05-07 21:00:08 +00005624bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005625 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005626}
Mike Stump11289f42009-09-09 15:08:12 +00005627
Peter Collingbournee9200682011-05-13 03:29:01 +00005628bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5629 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005630
Eli Friedman847a2bc2009-12-27 05:43:15 +00005631 switch (E->getCastKind()) {
5632 default:
5633 break;
5634
John McCalle3027922010-08-25 11:45:40 +00005635 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005636 case CK_CPointerToObjCPointerCast:
5637 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005638 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005639 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005640 if (!Visit(SubExpr))
5641 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005642 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5643 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5644 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005645 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005646 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005647 if (SubExpr->getType()->isVoidPointerType())
5648 CCEDiag(E, diag::note_constexpr_invalid_cast)
5649 << 3 << SubExpr->getType();
5650 else
5651 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5652 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005653 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5654 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005655 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005656
Anders Carlsson18275092010-10-31 20:41:46 +00005657 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005658 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005659 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005660 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005661 if (!Result.Base && Result.Offset.isZero())
5662 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005663
Richard Smithd62306a2011-11-10 06:34:14 +00005664 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005665 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005666 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5667 castAs<PointerType>()->getPointeeType(),
5668 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005669
Richard Smith027bf112011-11-17 22:56:20 +00005670 case CK_BaseToDerived:
5671 if (!Visit(E->getSubExpr()))
5672 return false;
5673 if (!Result.Base && Result.Offset.isZero())
5674 return true;
5675 return HandleBaseToDerivedCast(Info, E, Result);
5676
Richard Smith0b0a0b62011-10-29 20:57:55 +00005677 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005678 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005679 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005680
John McCalle3027922010-08-25 11:45:40 +00005681 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005682 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5683
Richard Smith2e312c82012-03-03 22:46:17 +00005684 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005685 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005686 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005687
John McCall45d55e42010-05-07 21:00:08 +00005688 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005689 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5690 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005691 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005692 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005693 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005694 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005695 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005696 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005697 return true;
5698 } else {
5699 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005700 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005701 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005702 }
5703 }
Richard Smith2cd56042017-08-29 01:52:13 +00005704
5705 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005706 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005707 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005708 return false;
5709 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005710 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005711 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005712 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005713 return false;
5714 }
Richard Smith96e0c102011-11-04 02:25:55 +00005715 // The result is a pointer to the first element of the array.
Richard Smith2cd56042017-08-29 01:52:13 +00005716 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5717 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005718 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005719 else
Richard Smith2cd56042017-08-29 01:52:13 +00005720 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005721 return true;
Richard Smith2cd56042017-08-29 01:52:13 +00005722 }
Richard Smithdd785442011-10-31 20:57:44 +00005723
John McCalle3027922010-08-25 11:45:40 +00005724 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005725 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005726
5727 case CK_LValueToRValue: {
5728 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005729 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005730 return false;
5731
5732 APValue RVal;
5733 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5734 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5735 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005736 return InvalidBaseOK &&
5737 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005738 return Success(RVal, E);
5739 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005740 }
5741
Richard Smith11562c52011-10-28 17:51:58 +00005742 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005743}
Chris Lattner05706e882008-07-11 18:11:29 +00005744
Hal Finkel0dd05d42014-10-03 17:18:37 +00005745static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5746 // C++ [expr.alignof]p3:
5747 // When alignof is applied to a reference type, the result is the
5748 // alignment of the referenced type.
5749 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5750 T = Ref->getPointeeType();
5751
5752 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005753 if (T.getQualifiers().hasUnaligned())
5754 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005755 return Info.Ctx.toCharUnitsFromBits(
5756 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5757}
5758
5759static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5760 E = E->IgnoreParens();
5761
5762 // The kinds of expressions that we have special-case logic here for
5763 // should be kept up to date with the special checks for those
5764 // expressions in Sema.
5765
5766 // alignof decl is always accepted, even if it doesn't make sense: we default
5767 // to 1 in those cases.
5768 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5769 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5770 /*RefAsPointee*/true);
5771
5772 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5773 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5774 /*RefAsPointee*/true);
5775
5776 return GetAlignOfType(Info, E->getType());
5777}
5778
George Burgess IVe3763372016-12-22 02:50:20 +00005779// To be clear: this happily visits unsupported builtins. Better name welcomed.
5780bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5781 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5782 return true;
5783
George Burgess IVf9013bf2017-02-10 22:52:29 +00005784 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005785 return false;
5786
5787 Result.setInvalid(E);
5788 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith2cd56042017-08-29 01:52:13 +00005789 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00005790 return true;
5791}
5792
Peter Collingbournee9200682011-05-13 03:29:01 +00005793bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005794 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005795 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005796
Richard Smith6328cbd2016-11-16 00:57:23 +00005797 if (unsigned BuiltinOp = E->getBuiltinCallee())
5798 return VisitBuiltinCallExpr(E, BuiltinOp);
5799
George Burgess IVe3763372016-12-22 02:50:20 +00005800 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005801}
5802
5803bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5804 unsigned BuiltinOp) {
5805 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005806 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005807 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005808 case Builtin::BI__builtin_assume_aligned: {
5809 // We need to be very careful here because: if the pointer does not have the
5810 // asserted alignment, then the behavior is undefined, and undefined
5811 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005812 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005813 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005814
Hal Finkel0dd05d42014-10-03 17:18:37 +00005815 LValue OffsetResult(Result);
5816 APSInt Alignment;
5817 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5818 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005819 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005820
5821 if (E->getNumArgs() > 2) {
5822 APSInt Offset;
5823 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5824 return false;
5825
Richard Smith642a2362017-01-30 23:30:26 +00005826 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005827 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5828 }
5829
5830 // If there is a base object, then it must have the correct alignment.
5831 if (OffsetResult.Base) {
5832 CharUnits BaseAlignment;
5833 if (const ValueDecl *VD =
5834 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5835 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5836 } else {
5837 BaseAlignment =
5838 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5839 }
5840
5841 if (BaseAlignment < Align) {
5842 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005843 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005844 CCEDiag(E->getArg(0),
5845 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005846 << (unsigned)BaseAlignment.getQuantity()
5847 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005848 return false;
5849 }
5850 }
5851
5852 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005853 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005854 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005855
Richard Smith642a2362017-01-30 23:30:26 +00005856 (OffsetResult.Base
5857 ? CCEDiag(E->getArg(0),
5858 diag::note_constexpr_baa_insufficient_alignment) << 1
5859 : CCEDiag(E->getArg(0),
5860 diag::note_constexpr_baa_value_insufficient_alignment))
5861 << (int)OffsetResult.Offset.getQuantity()
5862 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005863 return false;
5864 }
5865
5866 return true;
5867 }
Richard Smithe9507952016-11-12 01:39:56 +00005868
5869 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005870 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005871 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005872 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005873 if (Info.getLangOpts().CPlusPlus11)
5874 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5875 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005876 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005877 else
5878 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5879 // Fall through.
5880 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005881 case Builtin::BI__builtin_wcschr:
5882 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005883 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005884 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005885 if (!Visit(E->getArg(0)))
5886 return false;
5887 APSInt Desired;
5888 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5889 return false;
5890 uint64_t MaxLength = uint64_t(-1);
5891 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005892 BuiltinOp != Builtin::BIwcschr &&
5893 BuiltinOp != Builtin::BI__builtin_strchr &&
5894 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005895 APSInt N;
5896 if (!EvaluateInteger(E->getArg(2), N, Info))
5897 return false;
5898 MaxLength = N.getExtValue();
5899 }
5900
Richard Smith8110c9d2016-11-29 19:45:17 +00005901 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005902
Richard Smith8110c9d2016-11-29 19:45:17 +00005903 // Figure out what value we're actually looking for (after converting to
5904 // the corresponding unsigned type if necessary).
5905 uint64_t DesiredVal;
5906 bool StopAtNull = false;
5907 switch (BuiltinOp) {
5908 case Builtin::BIstrchr:
5909 case Builtin::BI__builtin_strchr:
5910 // strchr compares directly to the passed integer, and therefore
5911 // always fails if given an int that is not a char.
5912 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5913 E->getArg(1)->getType(),
5914 Desired),
5915 Desired))
5916 return ZeroInitialization(E);
5917 StopAtNull = true;
5918 // Fall through.
5919 case Builtin::BImemchr:
5920 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005921 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005922 // memchr compares by converting both sides to unsigned char. That's also
5923 // correct for strchr if we get this far (to cope with plain char being
5924 // unsigned in the strchr case).
5925 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5926 break;
Richard Smithe9507952016-11-12 01:39:56 +00005927
Richard Smith8110c9d2016-11-29 19:45:17 +00005928 case Builtin::BIwcschr:
5929 case Builtin::BI__builtin_wcschr:
5930 StopAtNull = true;
5931 // Fall through.
5932 case Builtin::BIwmemchr:
5933 case Builtin::BI__builtin_wmemchr:
5934 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5935 DesiredVal = Desired.getZExtValue();
5936 break;
5937 }
Richard Smithe9507952016-11-12 01:39:56 +00005938
5939 for (; MaxLength; --MaxLength) {
5940 APValue Char;
5941 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5942 !Char.isInt())
5943 return false;
5944 if (Char.getInt().getZExtValue() == DesiredVal)
5945 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005946 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005947 break;
5948 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5949 return false;
5950 }
5951 // Not found: return nullptr.
5952 return ZeroInitialization(E);
5953 }
5954
Richard Smith6cbd65d2013-07-11 02:27:57 +00005955 default:
George Burgess IVe3763372016-12-22 02:50:20 +00005956 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005957 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005958}
Chris Lattner05706e882008-07-11 18:11:29 +00005959
5960//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005961// Member Pointer Evaluation
5962//===----------------------------------------------------------------------===//
5963
5964namespace {
5965class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005966 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005967 MemberPtr &Result;
5968
5969 bool Success(const ValueDecl *D) {
5970 Result = MemberPtr(D);
5971 return true;
5972 }
5973public:
5974
5975 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5976 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5977
Richard Smith2e312c82012-03-03 22:46:17 +00005978 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005979 Result.setFrom(V);
5980 return true;
5981 }
Richard Smithfddd3842011-12-30 21:15:51 +00005982 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005983 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005984 }
5985
5986 bool VisitCastExpr(const CastExpr *E);
5987 bool VisitUnaryAddrOf(const UnaryOperator *E);
5988};
5989} // end anonymous namespace
5990
5991static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5992 EvalInfo &Info) {
5993 assert(E->isRValue() && E->getType()->isMemberPointerType());
5994 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5995}
5996
5997bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5998 switch (E->getCastKind()) {
5999 default:
6000 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6001
6002 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006003 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006004 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006005
6006 case CK_BaseToDerivedMemberPointer: {
6007 if (!Visit(E->getSubExpr()))
6008 return false;
6009 if (E->path_empty())
6010 return true;
6011 // Base-to-derived member pointer casts store the path in derived-to-base
6012 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6013 // the wrong end of the derived->base arc, so stagger the path by one class.
6014 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6015 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6016 PathI != PathE; ++PathI) {
6017 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6018 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6019 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006020 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006021 }
6022 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6023 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006024 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006025 return true;
6026 }
6027
6028 case CK_DerivedToBaseMemberPointer:
6029 if (!Visit(E->getSubExpr()))
6030 return false;
6031 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6032 PathE = E->path_end(); PathI != PathE; ++PathI) {
6033 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6034 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6035 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006036 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006037 }
6038 return true;
6039 }
6040}
6041
6042bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6043 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6044 // member can be formed.
6045 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6046}
6047
6048//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006049// Record Evaluation
6050//===----------------------------------------------------------------------===//
6051
6052namespace {
6053 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006054 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006055 const LValue &This;
6056 APValue &Result;
6057 public:
6058
6059 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6060 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6061
Richard Smith2e312c82012-03-03 22:46:17 +00006062 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006063 Result = V;
6064 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006065 }
Richard Smithb8348f52016-05-12 22:16:28 +00006066 bool ZeroInitialization(const Expr *E) {
6067 return ZeroInitialization(E, E->getType());
6068 }
6069 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006070
Richard Smith52a980a2015-08-28 02:43:42 +00006071 bool VisitCallExpr(const CallExpr *E) {
6072 return handleCallExpr(E, Result, &This);
6073 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006074 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006075 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006076 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6077 return VisitCXXConstructExpr(E, E->getType());
6078 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006079 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006080 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006081 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006082 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006083 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006084}
Richard Smithd62306a2011-11-10 06:34:14 +00006085
Richard Smithfddd3842011-12-30 21:15:51 +00006086/// Perform zero-initialization on an object of non-union class type.
6087/// C++11 [dcl.init]p5:
6088/// To zero-initialize an object or reference of type T means:
6089/// [...]
6090/// -- if T is a (possibly cv-qualified) non-union class type,
6091/// each non-static data member and each base-class subobject is
6092/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006093static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6094 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006095 const LValue &This, APValue &Result) {
6096 assert(!RD->isUnion() && "Expected non-union class type");
6097 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6098 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006099 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006100
John McCalld7bca762012-05-01 00:38:49 +00006101 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006102 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6103
6104 if (CD) {
6105 unsigned Index = 0;
6106 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006107 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006108 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6109 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006110 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6111 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006112 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006113 Result.getStructBase(Index)))
6114 return false;
6115 }
6116 }
6117
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006118 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006119 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006120 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006121 continue;
6122
6123 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006124 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006125 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006126
David Blaikie2d7c57e2012-04-30 02:36:29 +00006127 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006128 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006129 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006130 return false;
6131 }
6132
6133 return true;
6134}
6135
Richard Smithb8348f52016-05-12 22:16:28 +00006136bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6137 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006138 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006139 if (RD->isUnion()) {
6140 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6141 // object's first non-static named data member is zero-initialized
6142 RecordDecl::field_iterator I = RD->field_begin();
6143 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006144 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006145 return true;
6146 }
6147
6148 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006149 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006150 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006151 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006152 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006153 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006154 }
6155
Richard Smith5d108602012-02-17 00:44:16 +00006156 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006157 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006158 return false;
6159 }
6160
Richard Smitha8105bc2012-01-06 16:39:00 +00006161 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006162}
6163
Richard Smithe97cbd72011-11-11 04:05:33 +00006164bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6165 switch (E->getCastKind()) {
6166 default:
6167 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6168
6169 case CK_ConstructorConversion:
6170 return Visit(E->getSubExpr());
6171
6172 case CK_DerivedToBase:
6173 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006174 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006175 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006176 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006177 if (!DerivedObject.isStruct())
6178 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006179
6180 // Derived-to-base rvalue conversion: just slice off the derived part.
6181 APValue *Value = &DerivedObject;
6182 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6183 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6184 PathE = E->path_end(); PathI != PathE; ++PathI) {
6185 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6186 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6187 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6188 RD = Base;
6189 }
6190 Result = *Value;
6191 return true;
6192 }
6193 }
6194}
6195
Richard Smithd62306a2011-11-10 06:34:14 +00006196bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006197 if (E->isTransparent())
6198 return Visit(E->getInit(0));
6199
Richard Smithd62306a2011-11-10 06:34:14 +00006200 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006201 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006202 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6203
6204 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006205 const FieldDecl *Field = E->getInitializedFieldInUnion();
6206 Result = APValue(Field);
6207 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006208 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006209
6210 // If the initializer list for a union does not contain any elements, the
6211 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006212 // FIXME: The element should be initialized from an initializer list.
6213 // Is this difference ever observable for initializer lists which
6214 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006215 ImplicitValueInitExpr VIE(Field->getType());
6216 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6217
Richard Smithd62306a2011-11-10 06:34:14 +00006218 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006219 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6220 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006221
6222 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6223 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6224 isa<CXXDefaultInitExpr>(InitExpr));
6225
Richard Smithb228a862012-02-15 02:18:13 +00006226 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006227 }
6228
Richard Smith872307e2016-03-08 22:17:41 +00006229 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006230 if (Result.isUninit())
6231 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6232 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006233 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006234 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006235
6236 // Initialize base classes.
6237 if (CXXRD) {
6238 for (const auto &Base : CXXRD->bases()) {
6239 assert(ElementNo < E->getNumInits() && "missing init for base class");
6240 const Expr *Init = E->getInit(ElementNo);
6241
6242 LValue Subobject = This;
6243 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6244 return false;
6245
6246 APValue &FieldVal = Result.getStructBase(ElementNo);
6247 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006248 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006249 return false;
6250 Success = false;
6251 }
6252 ++ElementNo;
6253 }
6254 }
6255
6256 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006257 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006258 // Anonymous bit-fields are not considered members of the class for
6259 // purposes of aggregate initialization.
6260 if (Field->isUnnamedBitfield())
6261 continue;
6262
6263 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006264
Richard Smith253c2a32012-01-27 01:14:48 +00006265 bool HaveInit = ElementNo < E->getNumInits();
6266
6267 // FIXME: Diagnostics here should point to the end of the initializer
6268 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006269 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006270 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006271 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006272
6273 // Perform an implicit value-initialization for members beyond the end of
6274 // the initializer list.
6275 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006276 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006277
Richard Smith852c9db2013-04-20 22:23:05 +00006278 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6279 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6280 isa<CXXDefaultInitExpr>(Init));
6281
Richard Smith49ca8aa2013-08-06 07:09:20 +00006282 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6283 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6284 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006285 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006286 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006287 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006288 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006289 }
6290 }
6291
Richard Smith253c2a32012-01-27 01:14:48 +00006292 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006293}
6294
Richard Smithb8348f52016-05-12 22:16:28 +00006295bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6296 QualType T) {
6297 // Note that E's type is not necessarily the type of our class here; we might
6298 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006299 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006300 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6301
Richard Smithfddd3842011-12-30 21:15:51 +00006302 bool ZeroInit = E->requiresZeroInitialization();
6303 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006304 // If we've already performed zero-initialization, we're already done.
6305 if (!Result.isUninit())
6306 return true;
6307
Richard Smithda3f4fd2014-03-05 23:32:50 +00006308 // We can get here in two different ways:
6309 // 1) We're performing value-initialization, and should zero-initialize
6310 // the object, or
6311 // 2) We're performing default-initialization of an object with a trivial
6312 // constexpr default constructor, in which case we should start the
6313 // lifetimes of all the base subobjects (there can be no data member
6314 // subobjects in this case) per [basic.life]p1.
6315 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006316 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006317 }
6318
Craig Topper36250ad2014-05-12 05:36:57 +00006319 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006320 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006321
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006322 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006323 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006324
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006325 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006326 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006327 if (const MaterializeTemporaryExpr *ME
6328 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6329 return Visit(ME->GetTemporaryExpr());
6330
Richard Smithb8348f52016-05-12 22:16:28 +00006331 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006332 return false;
6333
Craig Topper5fc8fc22014-08-27 06:28:36 +00006334 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006335 return HandleConstructorCall(E, This, Args,
6336 cast<CXXConstructorDecl>(Definition), Info,
6337 Result);
6338}
6339
6340bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6341 const CXXInheritedCtorInitExpr *E) {
6342 if (!Info.CurrentCall) {
6343 assert(Info.checkingPotentialConstantExpression());
6344 return false;
6345 }
6346
6347 const CXXConstructorDecl *FD = E->getConstructor();
6348 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6349 return false;
6350
6351 const FunctionDecl *Definition = nullptr;
6352 auto Body = FD->getBody(Definition);
6353
6354 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6355 return false;
6356
6357 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006358 cast<CXXConstructorDecl>(Definition), Info,
6359 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006360}
6361
Richard Smithcc1b96d2013-06-12 22:31:48 +00006362bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6363 const CXXStdInitializerListExpr *E) {
6364 const ConstantArrayType *ArrayType =
6365 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6366
6367 LValue Array;
6368 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6369 return false;
6370
6371 // Get a pointer to the first element of the array.
6372 Array.addArray(Info, E, ArrayType);
6373
6374 // FIXME: Perform the checks on the field types in SemaInit.
6375 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6376 RecordDecl::field_iterator Field = Record->field_begin();
6377 if (Field == Record->field_end())
6378 return Error(E);
6379
6380 // Start pointer.
6381 if (!Field->getType()->isPointerType() ||
6382 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6383 ArrayType->getElementType()))
6384 return Error(E);
6385
6386 // FIXME: What if the initializer_list type has base classes, etc?
6387 Result = APValue(APValue::UninitStruct(), 0, 2);
6388 Array.moveInto(Result.getStructField(0));
6389
6390 if (++Field == Record->field_end())
6391 return Error(E);
6392
6393 if (Field->getType()->isPointerType() &&
6394 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6395 ArrayType->getElementType())) {
6396 // End pointer.
6397 if (!HandleLValueArrayAdjustment(Info, E, Array,
6398 ArrayType->getElementType(),
6399 ArrayType->getSize().getZExtValue()))
6400 return false;
6401 Array.moveInto(Result.getStructField(1));
6402 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6403 // Length.
6404 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6405 else
6406 return Error(E);
6407
6408 if (++Field != Record->field_end())
6409 return Error(E);
6410
6411 return true;
6412}
6413
Faisal Valic72a08c2017-01-09 03:02:53 +00006414bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6415 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6416 if (ClosureClass->isInvalidDecl()) return false;
6417
6418 if (Info.checkingPotentialConstantExpression()) return true;
Daniel Jasperffdee092017-05-02 19:21:42 +00006419
Faisal Vali051e3a22017-02-16 04:12:21 +00006420 const size_t NumFields =
6421 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006422
6423 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6424 E->capture_init_end()) &&
6425 "The number of lambda capture initializers should equal the number of "
6426 "fields within the closure type");
6427
Faisal Vali051e3a22017-02-16 04:12:21 +00006428 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6429 // Iterate through all the lambda's closure object's fields and initialize
6430 // them.
6431 auto *CaptureInitIt = E->capture_init_begin();
6432 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6433 bool Success = true;
6434 for (const auto *Field : ClosureClass->fields()) {
6435 assert(CaptureInitIt != E->capture_init_end());
6436 // Get the initializer for this field
6437 Expr *const CurFieldInit = *CaptureInitIt++;
Daniel Jasperffdee092017-05-02 19:21:42 +00006438
Faisal Vali051e3a22017-02-16 04:12:21 +00006439 // If there is no initializer, either this is a VLA or an error has
6440 // occurred.
6441 if (!CurFieldInit)
6442 return Error(E);
6443
6444 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6445 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6446 if (!Info.keepEvaluatingAfterFailure())
6447 return false;
6448 Success = false;
6449 }
6450 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006451 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006452 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006453}
6454
Richard Smithd62306a2011-11-10 06:34:14 +00006455static bool EvaluateRecord(const Expr *E, const LValue &This,
6456 APValue &Result, EvalInfo &Info) {
6457 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006458 "can't evaluate expression as a record rvalue");
6459 return RecordExprEvaluator(Info, This, Result).Visit(E);
6460}
6461
6462//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006463// Temporary Evaluation
6464//
6465// Temporaries are represented in the AST as rvalues, but generally behave like
6466// lvalues. The full-object of which the temporary is a subobject is implicitly
6467// materialized so that a reference can bind to it.
6468//===----------------------------------------------------------------------===//
6469namespace {
6470class TemporaryExprEvaluator
6471 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6472public:
6473 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006474 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006475
6476 /// Visit an expression which constructs the value of this temporary.
6477 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006478 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006479 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6480 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006481 }
6482
6483 bool VisitCastExpr(const CastExpr *E) {
6484 switch (E->getCastKind()) {
6485 default:
6486 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6487
6488 case CK_ConstructorConversion:
6489 return VisitConstructExpr(E->getSubExpr());
6490 }
6491 }
6492 bool VisitInitListExpr(const InitListExpr *E) {
6493 return VisitConstructExpr(E);
6494 }
6495 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6496 return VisitConstructExpr(E);
6497 }
6498 bool VisitCallExpr(const CallExpr *E) {
6499 return VisitConstructExpr(E);
6500 }
Richard Smith513955c2014-12-17 19:24:30 +00006501 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6502 return VisitConstructExpr(E);
6503 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006504 bool VisitLambdaExpr(const LambdaExpr *E) {
6505 return VisitConstructExpr(E);
6506 }
Richard Smith027bf112011-11-17 22:56:20 +00006507};
6508} // end anonymous namespace
6509
6510/// Evaluate an expression of record type as a temporary.
6511static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006512 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006513 return TemporaryExprEvaluator(Info, Result).Visit(E);
6514}
6515
6516//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006517// Vector Evaluation
6518//===----------------------------------------------------------------------===//
6519
6520namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006521 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006522 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006523 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006524 public:
Mike Stump11289f42009-09-09 15:08:12 +00006525
Richard Smith2d406342011-10-22 21:10:00 +00006526 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6527 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006528
Craig Topper9798b932015-09-29 04:30:05 +00006529 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006530 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6531 // FIXME: remove this APValue copy.
6532 Result = APValue(V.data(), V.size());
6533 return true;
6534 }
Richard Smith2e312c82012-03-03 22:46:17 +00006535 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006536 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006537 Result = V;
6538 return true;
6539 }
Richard Smithfddd3842011-12-30 21:15:51 +00006540 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006541
Richard Smith2d406342011-10-22 21:10:00 +00006542 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006543 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006544 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006545 bool VisitInitListExpr(const InitListExpr *E);
6546 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006547 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006548 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006549 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006550 };
6551} // end anonymous namespace
6552
6553static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006554 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006555 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006556}
6557
George Burgess IV533ff002015-12-11 00:23:35 +00006558bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006559 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006560 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006561
Richard Smith161f09a2011-12-06 22:44:34 +00006562 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006563 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006564
Eli Friedmanc757de22011-03-25 00:43:55 +00006565 switch (E->getCastKind()) {
6566 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006567 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006568 if (SETy->isIntegerType()) {
6569 APSInt IntResult;
6570 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006571 return false;
6572 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006573 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006574 APFloat FloatResult(0.0);
6575 if (!EvaluateFloat(SE, FloatResult, Info))
6576 return false;
6577 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006578 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006579 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006580 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006581
6582 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006583 SmallVector<APValue, 4> Elts(NElts, Val);
6584 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006585 }
Eli Friedman803acb32011-12-22 03:51:45 +00006586 case CK_BitCast: {
6587 // Evaluate the operand into an APInt we can extract from.
6588 llvm::APInt SValInt;
6589 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6590 return false;
6591 // Extract the elements
6592 QualType EltTy = VTy->getElementType();
6593 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6594 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6595 SmallVector<APValue, 4> Elts;
6596 if (EltTy->isRealFloatingType()) {
6597 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006598 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006599 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006600 FloatEltSize = 80;
6601 for (unsigned i = 0; i < NElts; i++) {
6602 llvm::APInt Elt;
6603 if (BigEndian)
6604 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6605 else
6606 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006607 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006608 }
6609 } else if (EltTy->isIntegerType()) {
6610 for (unsigned i = 0; i < NElts; i++) {
6611 llvm::APInt Elt;
6612 if (BigEndian)
6613 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6614 else
6615 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6616 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6617 }
6618 } else {
6619 return Error(E);
6620 }
6621 return Success(Elts, E);
6622 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006623 default:
Richard Smith11562c52011-10-28 17:51:58 +00006624 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006625 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006626}
6627
Richard Smith2d406342011-10-22 21:10:00 +00006628bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006629VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006630 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006631 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006632 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006633
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006634 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006635 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006636
Eli Friedmanb9c71292012-01-03 23:24:20 +00006637 // The number of initializers can be less than the number of
6638 // vector elements. For OpenCL, this can be due to nested vector
Daniel Jasperffdee092017-05-02 19:21:42 +00006639 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00006640 // should be initialized with zeroes.
6641 unsigned CountInits = 0, CountElts = 0;
6642 while (CountElts < NumElements) {
6643 // Handle nested vector initialization.
Daniel Jasperffdee092017-05-02 19:21:42 +00006644 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006645 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006646 APValue v;
6647 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6648 return Error(E);
6649 unsigned vlen = v.getVectorLength();
Daniel Jasperffdee092017-05-02 19:21:42 +00006650 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00006651 Elements.push_back(v.getVectorElt(j));
6652 CountElts += vlen;
6653 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006654 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006655 if (CountInits < NumInits) {
6656 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006657 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006658 } else // trailing integer zero.
6659 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6660 Elements.push_back(APValue(sInt));
6661 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006662 } else {
6663 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006664 if (CountInits < NumInits) {
6665 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006666 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006667 } else // trailing float zero.
6668 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6669 Elements.push_back(APValue(f));
6670 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006671 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006672 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006673 }
Richard Smith2d406342011-10-22 21:10:00 +00006674 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006675}
6676
Richard Smith2d406342011-10-22 21:10:00 +00006677bool
Richard Smithfddd3842011-12-30 21:15:51 +00006678VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006679 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006680 QualType EltTy = VT->getElementType();
6681 APValue ZeroElement;
6682 if (EltTy->isIntegerType())
6683 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6684 else
6685 ZeroElement =
6686 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6687
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006688 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006689 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006690}
6691
Richard Smith2d406342011-10-22 21:10:00 +00006692bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006693 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006694 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006695}
6696
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006697//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006698// Array Evaluation
6699//===----------------------------------------------------------------------===//
6700
6701namespace {
6702 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006703 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006704 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006705 APValue &Result;
6706 public:
6707
Richard Smithd62306a2011-11-10 06:34:14 +00006708 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6709 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006710
6711 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006712 assert((V.isArray() || V.isLValue()) &&
6713 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006714 Result = V;
6715 return true;
6716 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006717
Richard Smithfddd3842011-12-30 21:15:51 +00006718 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006719 const ConstantArrayType *CAT =
6720 Info.Ctx.getAsConstantArrayType(E->getType());
6721 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006722 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006723
6724 Result = APValue(APValue::UninitArray(), 0,
6725 CAT->getSize().getZExtValue());
6726 if (!Result.hasArrayFiller()) return true;
6727
Richard Smithfddd3842011-12-30 21:15:51 +00006728 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006729 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006730 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006731 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006732 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006733 }
6734
Richard Smith52a980a2015-08-28 02:43:42 +00006735 bool VisitCallExpr(const CallExpr *E) {
6736 return handleCallExpr(E, Result, &This);
6737 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006738 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006739 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006740 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006741 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6742 const LValue &Subobject,
6743 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006744 };
6745} // end anonymous namespace
6746
Richard Smithd62306a2011-11-10 06:34:14 +00006747static bool EvaluateArray(const Expr *E, const LValue &This,
6748 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006749 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006750 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006751}
6752
6753bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6754 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6755 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006756 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006757
Richard Smithca2cfbf2011-12-22 01:07:19 +00006758 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6759 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006760 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006761 LValue LV;
6762 if (!EvaluateLValue(E->getInit(0), LV, Info))
6763 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006764 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006765 LV.moveInto(Val);
6766 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006767 }
6768
Richard Smith253c2a32012-01-27 01:14:48 +00006769 bool Success = true;
6770
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006771 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6772 "zero-initialized array shouldn't have any initialized elts");
6773 APValue Filler;
6774 if (Result.isArray() && Result.hasArrayFiller())
6775 Filler = Result.getArrayFiller();
6776
Richard Smith9543c5e2013-04-22 14:44:29 +00006777 unsigned NumEltsToInit = E->getNumInits();
6778 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006779 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006780
6781 // If the initializer might depend on the array index, run it for each
6782 // array element. For now, just whitelist non-class value-initialization.
6783 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6784 NumEltsToInit = NumElts;
6785
6786 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006787
6788 // If the array was previously zero-initialized, preserve the
6789 // zero-initialized values.
6790 if (!Filler.isUninit()) {
6791 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6792 Result.getArrayInitializedElt(I) = Filler;
6793 if (Result.hasArrayFiller())
6794 Result.getArrayFiller() = Filler;
6795 }
6796
Richard Smithd62306a2011-11-10 06:34:14 +00006797 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006798 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006799 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6800 const Expr *Init =
6801 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006802 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006803 Info, Subobject, Init) ||
6804 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006805 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006806 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006807 return false;
6808 Success = false;
6809 }
Richard Smithd62306a2011-11-10 06:34:14 +00006810 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006811
Richard Smith9543c5e2013-04-22 14:44:29 +00006812 if (!Result.hasArrayFiller())
6813 return Success;
6814
6815 // If we get here, we have a trivial filler, which we can just evaluate
6816 // once and splat over the rest of the array elements.
6817 assert(FillerExpr && "no array filler for incomplete init list");
6818 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6819 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006820}
6821
Richard Smith410306b2016-12-12 02:53:20 +00006822bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6823 if (E->getCommonExpr() &&
6824 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6825 Info, E->getCommonExpr()->getSourceExpr()))
6826 return false;
6827
6828 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6829
6830 uint64_t Elements = CAT->getSize().getZExtValue();
6831 Result = APValue(APValue::UninitArray(), Elements, Elements);
6832
6833 LValue Subobject = This;
6834 Subobject.addArray(Info, E, CAT);
6835
6836 bool Success = true;
6837 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6838 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6839 Info, Subobject, E->getSubExpr()) ||
6840 !HandleLValueArrayAdjustment(Info, E, Subobject,
6841 CAT->getElementType(), 1)) {
6842 if (!Info.noteFailure())
6843 return false;
6844 Success = false;
6845 }
6846 }
6847
6848 return Success;
6849}
6850
Richard Smith027bf112011-11-17 22:56:20 +00006851bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006852 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6853}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006854
Richard Smith9543c5e2013-04-22 14:44:29 +00006855bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6856 const LValue &Subobject,
6857 APValue *Value,
6858 QualType Type) {
6859 bool HadZeroInit = !Value->isUninit();
6860
6861 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6862 unsigned N = CAT->getSize().getZExtValue();
6863
6864 // Preserve the array filler if we had prior zero-initialization.
6865 APValue Filler =
6866 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6867 : APValue();
6868
6869 *Value = APValue(APValue::UninitArray(), N, N);
6870
6871 if (HadZeroInit)
6872 for (unsigned I = 0; I != N; ++I)
6873 Value->getArrayInitializedElt(I) = Filler;
6874
6875 // Initialize the elements.
6876 LValue ArrayElt = Subobject;
6877 ArrayElt.addArray(Info, E, CAT);
6878 for (unsigned I = 0; I != N; ++I)
6879 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6880 CAT->getElementType()) ||
6881 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6882 CAT->getElementType(), 1))
6883 return false;
6884
6885 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006886 }
Richard Smith027bf112011-11-17 22:56:20 +00006887
Richard Smith9543c5e2013-04-22 14:44:29 +00006888 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006889 return Error(E);
6890
Richard Smithb8348f52016-05-12 22:16:28 +00006891 return RecordExprEvaluator(Info, Subobject, *Value)
6892 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006893}
6894
Richard Smithf3e9e432011-11-07 09:22:26 +00006895//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006896// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006897//
6898// As a GNU extension, we support casting pointers to sufficiently-wide integer
6899// types and back in constant folding. Integer values are thus represented
6900// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006901//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006902
6903namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006904class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006905 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006906 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006907public:
Richard Smith2e312c82012-03-03 22:46:17 +00006908 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006909 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006910
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006911 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006912 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006913 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006914 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006915 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006916 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006917 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006918 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006919 return true;
6920 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006921 bool Success(const llvm::APSInt &SI, const Expr *E) {
6922 return Success(SI, E, Result);
6923 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006924
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006925 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00006926 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006927 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006928 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006929 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006930 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006931 Result.getInt().setIsUnsigned(
6932 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006933 return true;
6934 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006935 bool Success(const llvm::APInt &I, const Expr *E) {
6936 return Success(I, E, Result);
6937 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006938
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006939 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00006940 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006941 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006942 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006943 return true;
6944 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006945 bool Success(uint64_t Value, const Expr *E) {
6946 return Success(Value, E, Result);
6947 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006948
Ken Dyckdbc01912011-03-11 02:13:43 +00006949 bool Success(CharUnits Size, const Expr *E) {
6950 return Success(Size.getQuantity(), E);
6951 }
6952
Richard Smith2e312c82012-03-03 22:46:17 +00006953 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006954 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006955 Result = V;
6956 return true;
6957 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006958 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006959 }
Mike Stump11289f42009-09-09 15:08:12 +00006960
Richard Smithfddd3842011-12-30 21:15:51 +00006961 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006962
Peter Collingbournee9200682011-05-13 03:29:01 +00006963 //===--------------------------------------------------------------------===//
6964 // Visitor Methods
6965 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006966
Chris Lattner7174bf32008-07-12 00:38:25 +00006967 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006968 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006969 }
6970 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006971 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006972 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006973
6974 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6975 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006976 if (CheckReferencedDecl(E, E->getDecl()))
6977 return true;
6978
6979 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006980 }
6981 bool VisitMemberExpr(const MemberExpr *E) {
6982 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006983 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006984 return true;
6985 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006986
6987 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006988 }
6989
Peter Collingbournee9200682011-05-13 03:29:01 +00006990 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006991 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006992 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006993 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006994 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006995
Peter Collingbournee9200682011-05-13 03:29:01 +00006996 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006997 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006998
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006999 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007000 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007001 }
Mike Stump11289f42009-09-09 15:08:12 +00007002
Ted Kremeneke65b0862012-03-06 20:05:56 +00007003 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7004 return Success(E->getValue(), E);
7005 }
Richard Smith410306b2016-12-12 02:53:20 +00007006
7007 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7008 if (Info.ArrayInitIndex == uint64_t(-1)) {
7009 // We were asked to evaluate this subexpression independent of the
7010 // enclosing ArrayInitLoopExpr. We can't do that.
7011 Info.FFDiag(E);
7012 return false;
7013 }
7014 return Success(Info.ArrayInitIndex, E);
7015 }
Daniel Jasperffdee092017-05-02 19:21:42 +00007016
Richard Smith4ce706a2011-10-11 21:43:33 +00007017 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007018 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007019 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007020 }
7021
Douglas Gregor29c42f22012-02-24 07:38:34 +00007022 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7023 return Success(E->getValue(), E);
7024 }
7025
John Wiegley6242b6a2011-04-28 00:16:57 +00007026 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7027 return Success(E->getValue(), E);
7028 }
7029
John Wiegleyf9f65842011-04-25 06:54:41 +00007030 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7031 return Success(E->getValue(), E);
7032 }
7033
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007034 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007035 bool VisitUnaryImag(const UnaryOperator *E);
7036
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007037 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007038 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007039
Eli Friedman4e7a2412009-02-27 04:45:43 +00007040 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007041};
Chris Lattner05706e882008-07-11 18:11:29 +00007042} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007043
Richard Smith11562c52011-10-28 17:51:58 +00007044/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7045/// produce either the integer value or a pointer.
7046///
7047/// GCC has a heinous extension which folds casts between pointer types and
7048/// pointer-sized integral types. We support this by allowing the evaluation of
7049/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7050/// Some simple arithmetic on such values is supported (they are treated much
7051/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007052static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007053 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007054 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007055 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007056}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007057
Richard Smithf57d8cb2011-12-09 22:58:01 +00007058static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007059 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007060 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007061 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007062 if (!Val.isInt()) {
7063 // FIXME: It would be better to produce the diagnostic for casting
7064 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007065 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007066 return false;
7067 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007068 Result = Val.getInt();
7069 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007070}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007071
Richard Smithf57d8cb2011-12-09 22:58:01 +00007072/// Check whether the given declaration can be directly converted to an integral
7073/// rvalue. If not, no diagnostic is produced; there are other things we can
7074/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007075bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007076 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007077 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007078 // Check for signedness/width mismatches between E type and ECD value.
7079 bool SameSign = (ECD->getInitVal().isSigned()
7080 == E->getType()->isSignedIntegerOrEnumerationType());
7081 bool SameWidth = (ECD->getInitVal().getBitWidth()
7082 == Info.Ctx.getIntWidth(E->getType()));
7083 if (SameSign && SameWidth)
7084 return Success(ECD->getInitVal(), E);
7085 else {
7086 // Get rid of mismatch (otherwise Success assertions will fail)
7087 // by computing a new value matching the type of E.
7088 llvm::APSInt Val = ECD->getInitVal();
7089 if (!SameSign)
7090 Val.setIsSigned(!ECD->getInitVal().isSigned());
7091 if (!SameWidth)
7092 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7093 return Success(Val, E);
7094 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007095 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007096 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007097}
7098
Chris Lattner86ee2862008-10-06 06:40:35 +00007099/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7100/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007101static int EvaluateBuiltinClassifyType(const CallExpr *E,
7102 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007103 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007104 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007105 enum gcc_type_class {
7106 no_type_class = -1,
7107 void_type_class, integer_type_class, char_type_class,
7108 enumeral_type_class, boolean_type_class,
7109 pointer_type_class, reference_type_class, offset_type_class,
7110 real_type_class, complex_type_class,
7111 function_type_class, method_type_class,
7112 record_type_class, union_type_class,
7113 array_type_class, string_type_class,
7114 lang_type_class
7115 };
Mike Stump11289f42009-09-09 15:08:12 +00007116
7117 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007118 // ideal, however it is what gcc does.
7119 if (E->getNumArgs() == 0)
7120 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007121
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007122 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7123 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7124
7125 switch (CanTy->getTypeClass()) {
7126#define TYPE(ID, BASE)
7127#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7128#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7129#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7130#include "clang/AST/TypeNodes.def"
7131 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7132
7133 case Type::Builtin:
7134 switch (BT->getKind()) {
7135#define BUILTIN_TYPE(ID, SINGLETON_ID)
7136#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7137#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7138#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7139#include "clang/AST/BuiltinTypes.def"
7140 case BuiltinType::Void:
7141 return void_type_class;
7142
7143 case BuiltinType::Bool:
7144 return boolean_type_class;
7145
7146 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7147 case BuiltinType::UChar:
7148 case BuiltinType::UShort:
7149 case BuiltinType::UInt:
7150 case BuiltinType::ULong:
7151 case BuiltinType::ULongLong:
7152 case BuiltinType::UInt128:
7153 return integer_type_class;
7154
7155 case BuiltinType::NullPtr:
7156 return pointer_type_class;
7157
7158 case BuiltinType::WChar_U:
7159 case BuiltinType::Char16:
7160 case BuiltinType::Char32:
7161 case BuiltinType::ObjCId:
7162 case BuiltinType::ObjCClass:
7163 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007164#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7165 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007166#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007167 case BuiltinType::OCLSampler:
7168 case BuiltinType::OCLEvent:
7169 case BuiltinType::OCLClkEvent:
7170 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007171 case BuiltinType::OCLReserveID:
7172 case BuiltinType::Dependent:
7173 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7174 };
7175
7176 case Type::Enum:
7177 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7178 break;
7179
7180 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007181 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007182 break;
7183
7184 case Type::MemberPointer:
7185 if (CanTy->isMemberDataPointerType())
7186 return offset_type_class;
7187 else {
7188 // We expect member pointers to be either data or function pointers,
7189 // nothing else.
7190 assert(CanTy->isMemberFunctionPointerType());
7191 return method_type_class;
7192 }
7193
7194 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007195 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007196
7197 case Type::FunctionNoProto:
7198 case Type::FunctionProto:
7199 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7200
7201 case Type::Record:
7202 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7203 switch (RT->getDecl()->getTagKind()) {
7204 case TagTypeKind::TTK_Struct:
7205 case TagTypeKind::TTK_Class:
7206 case TagTypeKind::TTK_Interface:
7207 return record_type_class;
7208
7209 case TagTypeKind::TTK_Enum:
7210 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7211
7212 case TagTypeKind::TTK_Union:
7213 return union_type_class;
7214 }
7215 }
David Blaikie83d382b2011-09-23 05:06:16 +00007216 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007217
7218 case Type::ConstantArray:
7219 case Type::VariableArray:
7220 case Type::IncompleteArray:
7221 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7222
7223 case Type::BlockPointer:
7224 case Type::LValueReference:
7225 case Type::RValueReference:
7226 case Type::Vector:
7227 case Type::ExtVector:
7228 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007229 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007230 case Type::ObjCObject:
7231 case Type::ObjCInterface:
7232 case Type::ObjCObjectPointer:
7233 case Type::Pipe:
7234 case Type::Atomic:
7235 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7236 }
7237
7238 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007239}
7240
Richard Smith5fab0c92011-12-28 19:48:30 +00007241/// EvaluateBuiltinConstantPForLValue - Determine the result of
7242/// __builtin_constant_p when applied to the given lvalue.
7243///
7244/// An lvalue is only "constant" if it is a pointer or reference to the first
7245/// character of a string literal.
7246template<typename LValue>
7247static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007248 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007249 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7250}
7251
7252/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7253/// GCC as we can manage.
7254static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7255 QualType ArgType = Arg->getType();
7256
7257 // __builtin_constant_p always has one operand. The rules which gcc follows
7258 // are not precisely documented, but are as follows:
7259 //
7260 // - If the operand is of integral, floating, complex or enumeration type,
7261 // and can be folded to a known value of that type, it returns 1.
7262 // - If the operand and can be folded to a pointer to the first character
7263 // of a string literal (or such a pointer cast to an integral type), it
7264 // returns 1.
7265 //
7266 // Otherwise, it returns 0.
7267 //
7268 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7269 // its support for this does not currently work.
7270 if (ArgType->isIntegralOrEnumerationType()) {
7271 Expr::EvalResult Result;
7272 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7273 return false;
7274
7275 APValue &V = Result.Val;
7276 if (V.getKind() == APValue::Int)
7277 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007278 if (V.getKind() == APValue::LValue)
7279 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007280 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7281 return Arg->isEvaluatable(Ctx);
7282 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7283 LValue LV;
7284 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007285 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007286 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7287 : EvaluatePointer(Arg, LV, Info)) &&
7288 !Status.HasSideEffects)
7289 return EvaluateBuiltinConstantPForLValue(LV);
7290 }
7291
7292 // Anything else isn't considered to be sufficiently constant.
7293 return false;
7294}
7295
John McCall95007602010-05-10 23:27:23 +00007296/// Retrieves the "underlying object type" of the given expression,
7297/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007298static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007299 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7300 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007301 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007302 } else if (const Expr *E = B.get<const Expr*>()) {
7303 if (isa<CompoundLiteralExpr>(E))
7304 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007305 }
7306
7307 return QualType();
7308}
7309
George Burgess IV3a03fab2015-09-04 21:28:13 +00007310/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007311/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007312/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007313/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7314///
7315/// Always returns an RValue with a pointer representation.
7316static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7317 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7318
7319 auto *NoParens = E->IgnoreParens();
7320 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007321 if (Cast == nullptr)
7322 return NoParens;
7323
7324 // We only conservatively allow a few kinds of casts, because this code is
7325 // inherently a simple solution that seeks to support the common case.
7326 auto CastKind = Cast->getCastKind();
7327 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7328 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007329 return NoParens;
7330
7331 auto *SubExpr = Cast->getSubExpr();
7332 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7333 return NoParens;
7334 return ignorePointerCastsAndParens(SubExpr);
7335}
7336
George Burgess IVa51c4072015-10-16 01:49:01 +00007337/// Checks to see if the given LValue's Designator is at the end of the LValue's
7338/// record layout. e.g.
7339/// struct { struct { int a, b; } fst, snd; } obj;
7340/// obj.fst // no
7341/// obj.snd // yes
7342/// obj.fst.a // no
7343/// obj.fst.b // no
7344/// obj.snd.a // no
7345/// obj.snd.b // yes
7346///
7347/// Please note: this function is specialized for how __builtin_object_size
7348/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007349///
Richard Smith2cd56042017-08-29 01:52:13 +00007350/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7351/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007352static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7353 assert(!LVal.Designator.Invalid);
7354
George Burgess IV4168d752016-06-27 19:40:41 +00007355 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7356 const RecordDecl *Parent = FD->getParent();
7357 Invalid = Parent->isInvalidDecl();
7358 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007359 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007360 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007361 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7362 };
7363
7364 auto &Base = LVal.getLValueBase();
7365 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7366 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007367 bool Invalid;
7368 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7369 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007370 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007371 for (auto *FD : IFD->chain()) {
7372 bool Invalid;
7373 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7374 return Invalid;
7375 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007376 }
7377 }
7378
George Burgess IVe3763372016-12-22 02:50:20 +00007379 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007380 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007381 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith2cd56042017-08-29 01:52:13 +00007382 // If we don't know the array bound, conservatively assume we're looking at
7383 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007384 ++I;
7385 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7386 }
7387
7388 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7389 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007390 if (BaseType->isArrayType()) {
7391 // Because __builtin_object_size treats arrays as objects, we can ignore
7392 // the index iff this is the last array in the Designator.
7393 if (I + 1 == E)
7394 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007395 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7396 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007397 if (Index + 1 != CAT->getSize())
7398 return false;
7399 BaseType = CAT->getElementType();
7400 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007401 const auto *CT = BaseType->castAs<ComplexType>();
7402 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007403 if (Index != 1)
7404 return false;
7405 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007406 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007407 bool Invalid;
7408 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7409 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007410 BaseType = FD->getType();
7411 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007412 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007413 return false;
7414 }
7415 }
7416 return true;
7417}
7418
George Burgess IVe3763372016-12-22 02:50:20 +00007419/// Tests to see if the LValue has a user-specified designator (that isn't
7420/// necessarily valid). Note that this always returns 'true' if the LValue has
7421/// an unsized array as its first designator entry, because there's currently no
7422/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007423static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007424 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007425 return false;
7426
George Burgess IVe3763372016-12-22 02:50:20 +00007427 if (!LVal.Designator.Entries.empty())
7428 return LVal.Designator.isMostDerivedAnUnsizedArray();
7429
George Burgess IVa51c4072015-10-16 01:49:01 +00007430 if (!LVal.InvalidBase)
7431 return true;
7432
George Burgess IVe3763372016-12-22 02:50:20 +00007433 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7434 // the LValueBase.
7435 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7436 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007437}
7438
George Burgess IVe3763372016-12-22 02:50:20 +00007439/// Attempts to detect a user writing into a piece of memory that's impossible
7440/// to figure out the size of by just using types.
7441static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7442 const SubobjectDesignator &Designator = LVal.Designator;
7443 // Notes:
7444 // - Users can only write off of the end when we have an invalid base. Invalid
7445 // bases imply we don't know where the memory came from.
7446 // - We used to be a bit more aggressive here; we'd only be conservative if
7447 // the array at the end was flexible, or if it had 0 or 1 elements. This
7448 // broke some common standard library extensions (PR30346), but was
7449 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7450 // with some sort of whitelist. OTOH, it seems that GCC is always
7451 // conservative with the last element in structs (if it's an array), so our
7452 // current behavior is more compatible than a whitelisting approach would
7453 // be.
7454 return LVal.InvalidBase &&
7455 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7456 Designator.MostDerivedIsArrayElement &&
7457 isDesignatorAtObjectEnd(Ctx, LVal);
7458}
7459
7460/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7461/// Fails if the conversion would cause loss of precision.
7462static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7463 CharUnits &Result) {
7464 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7465 if (Int.ugt(CharUnitsMax))
7466 return false;
7467 Result = CharUnits::fromQuantity(Int.getZExtValue());
7468 return true;
7469}
7470
7471/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7472/// determine how many bytes exist from the beginning of the object to either
7473/// the end of the current subobject, or the end of the object itself, depending
7474/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007475///
George Burgess IVe3763372016-12-22 02:50:20 +00007476/// If this returns false, the value of Result is undefined.
7477static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7478 unsigned Type, const LValue &LVal,
7479 CharUnits &EndOffset) {
7480 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007481
George Burgess IV7fb7e362017-01-03 23:35:19 +00007482 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7483 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7484 return false;
7485 return HandleSizeof(Info, ExprLoc, Ty, Result);
7486 };
7487
George Burgess IVe3763372016-12-22 02:50:20 +00007488 // We want to evaluate the size of the entire object. This is a valid fallback
7489 // for when Type=1 and the designator is invalid, because we're asked for an
7490 // upper-bound.
7491 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7492 // Type=3 wants a lower bound, so we can't fall back to this.
7493 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007494 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007495
7496 llvm::APInt APEndOffset;
7497 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7498 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7499 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7500
7501 if (LVal.InvalidBase)
7502 return false;
7503
7504 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007505 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007506 }
7507
George Burgess IVe3763372016-12-22 02:50:20 +00007508 // We want to evaluate the size of a subobject.
7509 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007510
7511 // The following is a moderately common idiom in C:
7512 //
7513 // struct Foo { int a; char c[1]; };
7514 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7515 // strcpy(&F->c[0], Bar);
7516 //
George Burgess IVe3763372016-12-22 02:50:20 +00007517 // In order to not break too much legacy code, we need to support it.
7518 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7519 // If we can resolve this to an alloc_size call, we can hand that back,
7520 // because we know for certain how many bytes there are to write to.
7521 llvm::APInt APEndOffset;
7522 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7523 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7524 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7525
7526 // If we cannot determine the size of the initial allocation, then we can't
7527 // given an accurate upper-bound. However, we are still able to give
7528 // conservative lower-bounds for Type=3.
7529 if (Type == 1)
7530 return false;
7531 }
7532
7533 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007534 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007535 return false;
7536
George Burgess IVe3763372016-12-22 02:50:20 +00007537 // According to the GCC documentation, we want the size of the subobject
7538 // denoted by the pointer. But that's not quite right -- what we actually
7539 // want is the size of the immediately-enclosing array, if there is one.
7540 int64_t ElemsRemaining;
7541 if (Designator.MostDerivedIsArrayElement &&
7542 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7543 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7544 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7545 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7546 } else {
7547 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7548 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007549
George Burgess IVe3763372016-12-22 02:50:20 +00007550 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7551 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007552}
7553
George Burgess IVe3763372016-12-22 02:50:20 +00007554/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7555/// returns true and stores the result in @p Size.
7556///
7557/// If @p WasError is non-null, this will report whether the failure to evaluate
7558/// is to be treated as an Error in IntExprEvaluator.
7559static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7560 EvalInfo &Info, uint64_t &Size) {
7561 // Determine the denoted object.
7562 LValue LVal;
7563 {
7564 // The operand of __builtin_object_size is never evaluated for side-effects.
7565 // If there are any, but we can determine the pointed-to object anyway, then
7566 // ignore the side-effects.
7567 SpeculativeEvaluationRAII SpeculativeEval(Info);
7568 FoldOffsetRAII Fold(Info);
7569
7570 if (E->isGLValue()) {
7571 // It's possible for us to be given GLValues if we're called via
7572 // Expr::tryEvaluateObjectSize.
7573 APValue RVal;
7574 if (!EvaluateAsRValue(Info, E, RVal))
7575 return false;
7576 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007577 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7578 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007579 return false;
7580 }
7581
7582 // If we point to before the start of the object, there are no accessible
7583 // bytes.
7584 if (LVal.getLValueOffset().isNegative()) {
7585 Size = 0;
7586 return true;
7587 }
7588
7589 CharUnits EndOffset;
7590 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7591 return false;
7592
7593 // If we've fallen outside of the end offset, just pretend there's nothing to
7594 // write to/read from.
7595 if (EndOffset <= LVal.getLValueOffset())
7596 Size = 0;
7597 else
7598 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7599 return true;
John McCall95007602010-05-10 23:27:23 +00007600}
7601
Peter Collingbournee9200682011-05-13 03:29:01 +00007602bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007603 if (unsigned BuiltinOp = E->getBuiltinCallee())
7604 return VisitBuiltinCallExpr(E, BuiltinOp);
7605
7606 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7607}
7608
7609bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7610 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007611 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007612 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007613 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007614
7615 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007616 // The type was checked when we built the expression.
7617 unsigned Type =
7618 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7619 assert(Type <= 3 && "unexpected type");
7620
George Burgess IVe3763372016-12-22 02:50:20 +00007621 uint64_t Size;
7622 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7623 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007624
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007625 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007626 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007627
Richard Smith01ade172012-05-23 04:13:20 +00007628 // Expression had no side effects, but we couldn't statically determine the
7629 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007630 switch (Info.EvalMode) {
7631 case EvalInfo::EM_ConstantExpression:
7632 case EvalInfo::EM_PotentialConstantExpression:
7633 case EvalInfo::EM_ConstantFold:
7634 case EvalInfo::EM_EvaluateForOverflow:
7635 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007636 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007637 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007638 return Error(E);
7639 case EvalInfo::EM_ConstantExpressionUnevaluated:
7640 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007641 // Reduce it to a constant now.
7642 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007643 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007644
7645 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007646 }
7647
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007648 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007649 case Builtin::BI__builtin_bswap32:
7650 case Builtin::BI__builtin_bswap64: {
7651 APSInt Val;
7652 if (!EvaluateInteger(E->getArg(0), Val, Info))
7653 return false;
7654
7655 return Success(Val.byteSwap(), E);
7656 }
7657
Richard Smith8889a3d2013-06-13 06:26:32 +00007658 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007659 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007660
7661 // FIXME: BI__builtin_clrsb
7662 // FIXME: BI__builtin_clrsbl
7663 // FIXME: BI__builtin_clrsbll
7664
Richard Smith80b3c8e2013-06-13 05:04:16 +00007665 case Builtin::BI__builtin_clz:
7666 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007667 case Builtin::BI__builtin_clzll:
7668 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007669 APSInt Val;
7670 if (!EvaluateInteger(E->getArg(0), Val, Info))
7671 return false;
7672 if (!Val)
7673 return Error(E);
7674
7675 return Success(Val.countLeadingZeros(), E);
7676 }
7677
Richard Smith8889a3d2013-06-13 06:26:32 +00007678 case Builtin::BI__builtin_constant_p:
7679 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7680
Richard Smith80b3c8e2013-06-13 05:04:16 +00007681 case Builtin::BI__builtin_ctz:
7682 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007683 case Builtin::BI__builtin_ctzll:
7684 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007685 APSInt Val;
7686 if (!EvaluateInteger(E->getArg(0), Val, Info))
7687 return false;
7688 if (!Val)
7689 return Error(E);
7690
7691 return Success(Val.countTrailingZeros(), E);
7692 }
7693
Richard Smith8889a3d2013-06-13 06:26:32 +00007694 case Builtin::BI__builtin_eh_return_data_regno: {
7695 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7696 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7697 return Success(Operand, E);
7698 }
7699
7700 case Builtin::BI__builtin_expect:
7701 return Visit(E->getArg(0));
7702
7703 case Builtin::BI__builtin_ffs:
7704 case Builtin::BI__builtin_ffsl:
7705 case Builtin::BI__builtin_ffsll: {
7706 APSInt Val;
7707 if (!EvaluateInteger(E->getArg(0), Val, Info))
7708 return false;
7709
7710 unsigned N = Val.countTrailingZeros();
7711 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7712 }
7713
7714 case Builtin::BI__builtin_fpclassify: {
7715 APFloat Val(0.0);
7716 if (!EvaluateFloat(E->getArg(5), Val, Info))
7717 return false;
7718 unsigned Arg;
7719 switch (Val.getCategory()) {
7720 case APFloat::fcNaN: Arg = 0; break;
7721 case APFloat::fcInfinity: Arg = 1; break;
7722 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7723 case APFloat::fcZero: Arg = 4; break;
7724 }
7725 return Visit(E->getArg(Arg));
7726 }
7727
7728 case Builtin::BI__builtin_isinf_sign: {
7729 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007730 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007731 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7732 }
7733
Richard Smithea3019d2013-10-15 19:07:14 +00007734 case Builtin::BI__builtin_isinf: {
7735 APFloat Val(0.0);
7736 return EvaluateFloat(E->getArg(0), Val, Info) &&
7737 Success(Val.isInfinity() ? 1 : 0, E);
7738 }
7739
7740 case Builtin::BI__builtin_isfinite: {
7741 APFloat Val(0.0);
7742 return EvaluateFloat(E->getArg(0), Val, Info) &&
7743 Success(Val.isFinite() ? 1 : 0, E);
7744 }
7745
7746 case Builtin::BI__builtin_isnan: {
7747 APFloat Val(0.0);
7748 return EvaluateFloat(E->getArg(0), Val, Info) &&
7749 Success(Val.isNaN() ? 1 : 0, E);
7750 }
7751
7752 case Builtin::BI__builtin_isnormal: {
7753 APFloat Val(0.0);
7754 return EvaluateFloat(E->getArg(0), Val, Info) &&
7755 Success(Val.isNormal() ? 1 : 0, E);
7756 }
7757
Richard Smith8889a3d2013-06-13 06:26:32 +00007758 case Builtin::BI__builtin_parity:
7759 case Builtin::BI__builtin_parityl:
7760 case Builtin::BI__builtin_parityll: {
7761 APSInt Val;
7762 if (!EvaluateInteger(E->getArg(0), Val, Info))
7763 return false;
7764
7765 return Success(Val.countPopulation() % 2, E);
7766 }
7767
Richard Smith80b3c8e2013-06-13 05:04:16 +00007768 case Builtin::BI__builtin_popcount:
7769 case Builtin::BI__builtin_popcountl:
7770 case Builtin::BI__builtin_popcountll: {
7771 APSInt Val;
7772 if (!EvaluateInteger(E->getArg(0), Val, Info))
7773 return false;
7774
7775 return Success(Val.countPopulation(), E);
7776 }
7777
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007778 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007779 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007780 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007781 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007782 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007783 << /*isConstexpr*/0 << /*isConstructor*/0
7784 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007785 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007786 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007787 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007788 case Builtin::BI__builtin_strlen:
7789 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007790 // As an extension, we support __builtin_strlen() as a constant expression,
7791 // and support folding strlen() to a constant.
7792 LValue String;
7793 if (!EvaluatePointer(E->getArg(0), String, Info))
7794 return false;
7795
Richard Smith8110c9d2016-11-29 19:45:17 +00007796 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7797
Richard Smithe6c19f22013-11-15 02:10:04 +00007798 // Fast path: if it's a string literal, search the string value.
7799 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7800 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007801 // The string literal may have embedded null characters. Find the first
7802 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007803 StringRef Str = S->getBytes();
7804 int64_t Off = String.Offset.getQuantity();
7805 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007806 S->getCharByteWidth() == 1 &&
7807 // FIXME: Add fast-path for wchar_t too.
7808 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007809 Str = Str.substr(Off);
7810
7811 StringRef::size_type Pos = Str.find(0);
7812 if (Pos != StringRef::npos)
7813 Str = Str.substr(0, Pos);
7814
7815 return Success(Str.size(), E);
7816 }
7817
7818 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007819 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007820
7821 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007822 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7823 APValue Char;
7824 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7825 !Char.isInt())
7826 return false;
7827 if (!Char.getInt())
7828 return Success(Strlen, E);
7829 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7830 return false;
7831 }
7832 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007833
Richard Smithe151bab2016-11-11 23:43:35 +00007834 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007835 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007836 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007837 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007838 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007839 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007840 // A call to strlen is not a constant expression.
7841 if (Info.getLangOpts().CPlusPlus11)
7842 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7843 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007844 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007845 else
7846 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7847 // Fall through.
7848 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007849 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007850 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007851 case Builtin::BI__builtin_wcsncmp:
7852 case Builtin::BI__builtin_memcmp:
7853 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007854 LValue String1, String2;
7855 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7856 !EvaluatePointer(E->getArg(1), String2, Info))
7857 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007858
7859 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7860
Richard Smithe151bab2016-11-11 23:43:35 +00007861 uint64_t MaxLength = uint64_t(-1);
7862 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007863 BuiltinOp != Builtin::BIwcscmp &&
7864 BuiltinOp != Builtin::BI__builtin_strcmp &&
7865 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007866 APSInt N;
7867 if (!EvaluateInteger(E->getArg(2), N, Info))
7868 return false;
7869 MaxLength = N.getExtValue();
7870 }
7871 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007872 BuiltinOp != Builtin::BIwmemcmp &&
7873 BuiltinOp != Builtin::BI__builtin_memcmp &&
7874 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007875 for (; MaxLength; --MaxLength) {
7876 APValue Char1, Char2;
7877 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7878 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7879 !Char1.isInt() || !Char2.isInt())
7880 return false;
7881 if (Char1.getInt() != Char2.getInt())
7882 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7883 if (StopAtNull && !Char1.getInt())
7884 return Success(0, E);
7885 assert(!(StopAtNull && !Char2.getInt()));
7886 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7887 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7888 return false;
7889 }
7890 // We hit the strncmp / memcmp limit.
7891 return Success(0, E);
7892 }
7893
Richard Smith01ba47d2012-04-13 00:45:38 +00007894 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007895 case Builtin::BI__atomic_is_lock_free:
7896 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007897 APSInt SizeVal;
7898 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7899 return false;
7900
7901 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7902 // of two less than the maximum inline atomic width, we know it is
7903 // lock-free. If the size isn't a power of two, or greater than the
7904 // maximum alignment where we promote atomics, we know it is not lock-free
7905 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7906 // the answer can only be determined at runtime; for example, 16-byte
7907 // atomics have lock-free implementations on some, but not all,
7908 // x86-64 processors.
7909
7910 // Check power-of-two.
7911 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007912 if (Size.isPowerOfTwo()) {
7913 // Check against inlining width.
7914 unsigned InlineWidthBits =
7915 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7916 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7917 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7918 Size == CharUnits::One() ||
7919 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7920 Expr::NPC_NeverValueDependent))
7921 // OK, we will inline appropriately-aligned operations of this size,
7922 // and _Atomic(T) is appropriately-aligned.
7923 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007924
Richard Smith01ba47d2012-04-13 00:45:38 +00007925 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7926 castAs<PointerType>()->getPointeeType();
7927 if (!PointeeType->isIncompleteType() &&
7928 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7929 // OK, we will inline operations on this object.
7930 return Success(1, E);
7931 }
7932 }
7933 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007934
Richard Smith01ba47d2012-04-13 00:45:38 +00007935 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7936 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007937 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007938 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007939}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007940
Richard Smith8b3497e2011-10-31 01:37:14 +00007941static bool HasSameBase(const LValue &A, const LValue &B) {
7942 if (!A.getLValueBase())
7943 return !B.getLValueBase();
7944 if (!B.getLValueBase())
7945 return false;
7946
Richard Smithce40ad62011-11-12 22:28:03 +00007947 if (A.getLValueBase().getOpaqueValue() !=
7948 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007949 const Decl *ADecl = GetLValueBaseDecl(A);
7950 if (!ADecl)
7951 return false;
7952 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007953 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007954 return false;
7955 }
7956
7957 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007958 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007959}
7960
Richard Smithd20f1e62014-10-21 23:01:04 +00007961/// \brief Determine whether this is a pointer past the end of the complete
7962/// object referred to by the lvalue.
7963static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7964 const LValue &LV) {
7965 // A null pointer can be viewed as being "past the end" but we don't
7966 // choose to look at it that way here.
7967 if (!LV.getLValueBase())
7968 return false;
7969
7970 // If the designator is valid and refers to a subobject, we're not pointing
7971 // past the end.
7972 if (!LV.getLValueDesignator().Invalid &&
7973 !LV.getLValueDesignator().isOnePastTheEnd())
7974 return false;
7975
David Majnemerc378ca52015-08-29 08:32:55 +00007976 // A pointer to an incomplete type might be past-the-end if the type's size is
7977 // zero. We cannot tell because the type is incomplete.
7978 QualType Ty = getType(LV.getLValueBase());
7979 if (Ty->isIncompleteType())
7980 return true;
7981
Richard Smithd20f1e62014-10-21 23:01:04 +00007982 // We're a past-the-end pointer if we point to the byte after the object,
7983 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007984 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007985 return LV.getLValueOffset() == Size;
7986}
7987
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007988namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007989
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007990/// \brief Data recursive integer evaluator of certain binary operators.
7991///
7992/// We use a data recursive algorithm for binary operators so that we are able
7993/// to handle extreme cases of chained binary operators without causing stack
7994/// overflow.
7995class DataRecursiveIntBinOpEvaluator {
7996 struct EvalResult {
7997 APValue Val;
7998 bool Failed;
7999
8000 EvalResult() : Failed(false) { }
8001
8002 void swap(EvalResult &RHS) {
8003 Val.swap(RHS.Val);
8004 Failed = RHS.Failed;
8005 RHS.Failed = false;
8006 }
8007 };
8008
8009 struct Job {
8010 const Expr *E;
8011 EvalResult LHSResult; // meaningful only for binary operator expression.
8012 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008013
David Blaikie73726062015-08-12 23:09:24 +00008014 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008015 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008016
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008017 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008018 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008019 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008020
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008021 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008022 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008023 };
8024
8025 SmallVector<Job, 16> Queue;
8026
8027 IntExprEvaluator &IntEval;
8028 EvalInfo &Info;
8029 APValue &FinalResult;
8030
8031public:
8032 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8033 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8034
8035 /// \brief True if \param E is a binary operator that we are going to handle
8036 /// data recursively.
8037 /// We handle binary operators that are comma, logical, or that have operands
8038 /// with integral or enumeration type.
8039 static bool shouldEnqueue(const BinaryOperator *E) {
8040 return E->getOpcode() == BO_Comma ||
8041 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00008042 (E->isRValue() &&
8043 E->getType()->isIntegralOrEnumerationType() &&
8044 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008045 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008046 }
8047
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008048 bool Traverse(const BinaryOperator *E) {
8049 enqueue(E);
8050 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008051 while (!Queue.empty())
8052 process(PrevResult);
8053
8054 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008055
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008056 FinalResult.swap(PrevResult.Val);
8057 return true;
8058 }
8059
8060private:
8061 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8062 return IntEval.Success(Value, E, Result);
8063 }
8064 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8065 return IntEval.Success(Value, E, Result);
8066 }
8067 bool Error(const Expr *E) {
8068 return IntEval.Error(E);
8069 }
8070 bool Error(const Expr *E, diag::kind D) {
8071 return IntEval.Error(E, D);
8072 }
8073
8074 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8075 return Info.CCEDiag(E, D);
8076 }
8077
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008078 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8079 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008080 bool &SuppressRHSDiags);
8081
8082 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8083 const BinaryOperator *E, APValue &Result);
8084
8085 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8086 Result.Failed = !Evaluate(Result.Val, Info, E);
8087 if (Result.Failed)
8088 Result.Val = APValue();
8089 }
8090
Richard Trieuba4d0872012-03-21 23:30:30 +00008091 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008092
8093 void enqueue(const Expr *E) {
8094 E = E->IgnoreParens();
8095 Queue.resize(Queue.size()+1);
8096 Queue.back().E = E;
8097 Queue.back().Kind = Job::AnyExprKind;
8098 }
8099};
8100
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008101}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008102
8103bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008104 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008105 bool &SuppressRHSDiags) {
8106 if (E->getOpcode() == BO_Comma) {
8107 // Ignore LHS but note if we could not evaluate it.
8108 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008109 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008110 return true;
8111 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008112
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008113 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008114 bool LHSAsBool;
8115 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008116 // We were able to evaluate the LHS, see if we can get away with not
8117 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008118 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8119 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008120 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008121 }
8122 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008123 LHSResult.Failed = true;
8124
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008125 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008126 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008127 if (!Info.noteSideEffect())
8128 return false;
8129
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008130 // We can't evaluate the LHS; however, sometimes the result
8131 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8132 // Don't ignore RHS and suppress diagnostics from this arm.
8133 SuppressRHSDiags = true;
8134 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008135
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008136 return true;
8137 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008138
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008139 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8140 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008141
George Burgess IVa145e252016-05-25 22:38:36 +00008142 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008143 return false; // Ignore RHS;
8144
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008145 return true;
8146}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008147
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008148static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8149 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008150 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8151 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8152 // offsets.
8153 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8154 CharUnits &Offset = LVal.getLValueOffset();
8155 uint64_t Offset64 = Offset.getQuantity();
8156 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8157 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8158 : Offset64 + Index64);
8159}
8160
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008161bool DataRecursiveIntBinOpEvaluator::
8162 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8163 const BinaryOperator *E, APValue &Result) {
8164 if (E->getOpcode() == BO_Comma) {
8165 if (RHSResult.Failed)
8166 return false;
8167 Result = RHSResult.Val;
8168 return true;
8169 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008170
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008171 if (E->isLogicalOp()) {
8172 bool lhsResult, rhsResult;
8173 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8174 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Daniel Jasperffdee092017-05-02 19:21:42 +00008175
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008176 if (LHSIsOK) {
8177 if (RHSIsOK) {
8178 if (E->getOpcode() == BO_LOr)
8179 return Success(lhsResult || rhsResult, E, Result);
8180 else
8181 return Success(lhsResult && rhsResult, E, Result);
8182 }
8183 } else {
8184 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008185 // We can't evaluate the LHS; however, sometimes the result
8186 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8187 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008188 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008189 }
8190 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008191
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008192 return false;
8193 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008194
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008195 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8196 E->getRHS()->getType()->isIntegralOrEnumerationType());
Daniel Jasperffdee092017-05-02 19:21:42 +00008197
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008198 if (LHSResult.Failed || RHSResult.Failed)
8199 return false;
Daniel Jasperffdee092017-05-02 19:21:42 +00008200
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008201 const APValue &LHSVal = LHSResult.Val;
8202 const APValue &RHSVal = RHSResult.Val;
Daniel Jasperffdee092017-05-02 19:21:42 +00008203
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008204 // Handle cases like (unsigned long)&a + 4.
8205 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8206 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008207 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008208 return true;
8209 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008210
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008211 // Handle cases like 4 + (unsigned long)&a
8212 if (E->getOpcode() == BO_Add &&
8213 RHSVal.isLValue() && LHSVal.isInt()) {
8214 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008215 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008216 return true;
8217 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008218
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008219 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8220 // Handle (intptr_t)&&A - (intptr_t)&&B.
8221 if (!LHSVal.getLValueOffset().isZero() ||
8222 !RHSVal.getLValueOffset().isZero())
8223 return false;
8224 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8225 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8226 if (!LHSExpr || !RHSExpr)
8227 return false;
8228 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8229 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8230 if (!LHSAddrExpr || !RHSAddrExpr)
8231 return false;
8232 // Make sure both labels come from the same function.
8233 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8234 RHSAddrExpr->getLabel()->getDeclContext())
8235 return false;
8236 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8237 return true;
8238 }
Richard Smith43e77732013-05-07 04:50:00 +00008239
8240 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008241 if (!LHSVal.isInt() || !RHSVal.isInt())
8242 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008243
8244 // Set up the width and signedness manually, in case it can't be deduced
8245 // from the operation we're performing.
8246 // FIXME: Don't do this in the cases where we can deduce it.
8247 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8248 E->getType()->isUnsignedIntegerOrEnumerationType());
8249 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8250 RHSVal.getInt(), Value))
8251 return false;
8252 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008253}
8254
Richard Trieuba4d0872012-03-21 23:30:30 +00008255void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008256 Job &job = Queue.back();
Daniel Jasperffdee092017-05-02 19:21:42 +00008257
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008258 switch (job.Kind) {
8259 case Job::AnyExprKind: {
8260 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8261 if (shouldEnqueue(Bop)) {
8262 job.Kind = Job::BinOpKind;
8263 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008264 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008265 }
8266 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008267
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008268 EvaluateExpr(job.E, Result);
8269 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008270 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008271 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008272
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008273 case Job::BinOpKind: {
8274 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008275 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008276 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008277 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008278 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008279 }
8280 if (SuppressRHSDiags)
8281 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008282 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008283 job.Kind = Job::BinOpVisitedLHSKind;
8284 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008285 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008286 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008287
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008288 case Job::BinOpVisitedLHSKind: {
8289 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8290 EvalResult RHS;
8291 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008292 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008293 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008294 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008295 }
8296 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008297
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008298 llvm_unreachable("Invalid Job::Kind!");
8299}
8300
George Burgess IV8c892b52016-05-25 22:31:54 +00008301namespace {
8302/// Used when we determine that we should fail, but can keep evaluating prior to
8303/// noting that we had a failure.
8304class DelayedNoteFailureRAII {
8305 EvalInfo &Info;
8306 bool NoteFailure;
8307
8308public:
8309 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8310 : Info(Info), NoteFailure(NoteFailure) {}
8311 ~DelayedNoteFailureRAII() {
8312 if (NoteFailure) {
8313 bool ContinueAfterFailure = Info.noteFailure();
8314 (void)ContinueAfterFailure;
8315 assert(ContinueAfterFailure &&
8316 "Shouldn't have kept evaluating on failure.");
8317 }
8318 }
8319};
8320}
8321
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008322bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008323 // We don't call noteFailure immediately because the assignment happens after
8324 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008325 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008326 return Error(E);
8327
George Burgess IV8c892b52016-05-25 22:31:54 +00008328 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008329 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8330 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008331
Anders Carlssonacc79812008-11-16 07:17:21 +00008332 QualType LHSTy = E->getLHS()->getType();
8333 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008334
Chandler Carruthb29a7432014-10-11 11:03:30 +00008335 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008336 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008337 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008338 if (E->isAssignmentOp()) {
8339 LValue LV;
8340 EvaluateLValue(E->getLHS(), LV, Info);
8341 LHSOK = false;
8342 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008343 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8344 if (LHSOK) {
8345 LHS.makeComplexFloat();
8346 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8347 }
8348 } else {
8349 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8350 }
George Burgess IVa145e252016-05-25 22:38:36 +00008351 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008352 return false;
8353
Chandler Carruthb29a7432014-10-11 11:03:30 +00008354 if (E->getRHS()->getType()->isRealFloatingType()) {
8355 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8356 return false;
8357 RHS.makeComplexFloat();
8358 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8359 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008360 return false;
8361
8362 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008363 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008364 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008365 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008366 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8367
John McCalle3027922010-08-25 11:45:40 +00008368 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008369 return Success((CR_r == APFloat::cmpEqual &&
8370 CR_i == APFloat::cmpEqual), E);
8371 else {
John McCalle3027922010-08-25 11:45:40 +00008372 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008373 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008374 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008375 CR_r == APFloat::cmpLessThan ||
8376 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008377 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008378 CR_i == APFloat::cmpLessThan ||
8379 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008380 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008381 } else {
John McCalle3027922010-08-25 11:45:40 +00008382 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008383 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8384 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8385 else {
John McCalle3027922010-08-25 11:45:40 +00008386 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008387 "Invalid compex comparison.");
8388 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8389 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8390 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008391 }
8392 }
Mike Stump11289f42009-09-09 15:08:12 +00008393
Anders Carlssonacc79812008-11-16 07:17:21 +00008394 if (LHSTy->isRealFloatingType() &&
8395 RHSTy->isRealFloatingType()) {
8396 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008397
Richard Smith253c2a32012-01-27 01:14:48 +00008398 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008399 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008400 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008401
Richard Smith253c2a32012-01-27 01:14:48 +00008402 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008403 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008404
Anders Carlssonacc79812008-11-16 07:17:21 +00008405 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008406
Anders Carlssonacc79812008-11-16 07:17:21 +00008407 switch (E->getOpcode()) {
8408 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008409 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008410 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008411 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008412 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008413 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008414 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008415 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008416 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008417 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008418 E);
John McCalle3027922010-08-25 11:45:40 +00008419 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008420 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008421 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008422 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008423 || CR == APFloat::cmpLessThan
8424 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008425 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008426 }
Mike Stump11289f42009-09-09 15:08:12 +00008427
Eli Friedmana38da572009-04-28 19:17:36 +00008428 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008429 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008430 LValue LHSValue, RHSValue;
8431
8432 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008433 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008434 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008435
Richard Smith253c2a32012-01-27 01:14:48 +00008436 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008437 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008438
Richard Smith8b3497e2011-10-31 01:37:14 +00008439 // Reject differing bases from the normal codepath; we special-case
8440 // comparisons to null.
8441 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008442 if (E->getOpcode() == BO_Sub) {
8443 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008444 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008445 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008446 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008447 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008448 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008449 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008450 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8451 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8452 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008453 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008454 // Make sure both labels come from the same function.
8455 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8456 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008457 return Error(E);
8458 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008459 }
Richard Smith83c68212011-10-31 05:11:32 +00008460 // Inequalities and subtractions between unrelated pointers have
8461 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008462 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008463 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008464 // A constant address may compare equal to the address of a symbol.
8465 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008466 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008467 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8468 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008469 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008470 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008471 // distinct addresses. In clang, the result of such a comparison is
8472 // unspecified, so it is not a constant expression. However, we do know
8473 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008474 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8475 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008476 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008477 // We can't tell whether weak symbols will end up pointing to the same
8478 // object.
8479 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008480 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008481 // We can't compare the address of the start of one object with the
8482 // past-the-end address of another object, per C++ DR1652.
8483 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8484 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8485 (RHSValue.Base && RHSValue.Offset.isZero() &&
8486 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8487 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008488 // We can't tell whether an object is at the same address as another
8489 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008490 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8491 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008492 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008493 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008494 // (Note that clang defaults to -fmerge-all-constants, which can
8495 // lead to inconsistent results for comparisons involving the address
8496 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008497 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008498 }
Eli Friedman64004332009-03-23 04:38:34 +00008499
Richard Smith1b470412012-02-01 08:10:20 +00008500 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8501 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8502
Richard Smith84f6dcf2012-02-02 01:16:57 +00008503 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8504 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8505
John McCalle3027922010-08-25 11:45:40 +00008506 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008507 // C++11 [expr.add]p6:
8508 // Unless both pointers point to elements of the same array object, or
8509 // one past the last element of the array object, the behavior is
8510 // undefined.
8511 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8512 !AreElementsOfSameArray(getType(LHSValue.Base),
8513 LHSDesignator, RHSDesignator))
8514 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8515
Chris Lattner882bdf22010-04-20 17:13:14 +00008516 QualType Type = E->getLHS()->getType();
8517 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008518
Richard Smithd62306a2011-11-10 06:34:14 +00008519 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008520 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008521 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008522
Richard Smith84c6b3d2013-09-10 21:34:14 +00008523 // As an extension, a type may have zero size (empty struct or union in
8524 // C, array of zero length). Pointer subtraction in such cases has
8525 // undefined behavior, so is not constant.
8526 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008527 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008528 << ElementType;
8529 return false;
8530 }
8531
Richard Smith1b470412012-02-01 08:10:20 +00008532 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8533 // and produce incorrect results when it overflows. Such behavior
8534 // appears to be non-conforming, but is common, so perhaps we should
8535 // assume the standard intended for such cases to be undefined behavior
8536 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008537
Richard Smith1b470412012-02-01 08:10:20 +00008538 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8539 // overflow in the final conversion to ptrdiff_t.
8540 APSInt LHS(
8541 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8542 APSInt RHS(
8543 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8544 APSInt ElemSize(
8545 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8546 APSInt TrueResult = (LHS - RHS) / ElemSize;
8547 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8548
Richard Smith0c6124b2015-12-03 01:36:22 +00008549 if (Result.extend(65) != TrueResult &&
8550 !HandleOverflow(Info, E, TrueResult, E->getType()))
8551 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008552 return Success(Result, E);
8553 }
Richard Smithde21b242012-01-31 06:41:30 +00008554
8555 // C++11 [expr.rel]p3:
8556 // Pointers to void (after pointer conversions) can be compared, with a
8557 // result defined as follows: If both pointers represent the same
8558 // address or are both the null pointer value, the result is true if the
8559 // operator is <= or >= and false otherwise; otherwise the result is
8560 // unspecified.
8561 // We interpret this as applying to pointers to *cv* void.
8562 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008563 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008564 CCEDiag(E, diag::note_constexpr_void_comparison);
8565
Richard Smith84f6dcf2012-02-02 01:16:57 +00008566 // C++11 [expr.rel]p2:
8567 // - If two pointers point to non-static data members of the same object,
8568 // or to subobjects or array elements fo such members, recursively, the
8569 // pointer to the later declared member compares greater provided the
8570 // two members have the same access control and provided their class is
8571 // not a union.
8572 // [...]
8573 // - Otherwise pointer comparisons are unspecified.
8574 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8575 E->isRelationalOp()) {
8576 bool WasArrayIndex;
8577 unsigned Mismatch =
8578 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8579 RHSDesignator, WasArrayIndex);
8580 // At the point where the designators diverge, the comparison has a
8581 // specified value if:
8582 // - we are comparing array indices
8583 // - we are comparing fields of a union, or fields with the same access
8584 // Otherwise, the result is unspecified and thus the comparison is not a
8585 // constant expression.
8586 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8587 Mismatch < RHSDesignator.Entries.size()) {
8588 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8589 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8590 if (!LF && !RF)
8591 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8592 else if (!LF)
8593 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8594 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8595 << RF->getParent() << RF;
8596 else if (!RF)
8597 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8598 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8599 << LF->getParent() << LF;
8600 else if (!LF->getParent()->isUnion() &&
8601 LF->getAccess() != RF->getAccess())
8602 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8603 << LF << LF->getAccess() << RF << RF->getAccess()
8604 << LF->getParent();
8605 }
8606 }
8607
Eli Friedman6c31cb42012-04-16 04:30:08 +00008608 // The comparison here must be unsigned, and performed with the same
8609 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008610 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8611 uint64_t CompareLHS = LHSOffset.getQuantity();
8612 uint64_t CompareRHS = RHSOffset.getQuantity();
8613 assert(PtrSize <= 64 && "Unexpected pointer width");
8614 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8615 CompareLHS &= Mask;
8616 CompareRHS &= Mask;
8617
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008618 // If there is a base and this is a relational operator, we can only
8619 // compare pointers within the object in question; otherwise, the result
8620 // depends on where the object is located in memory.
8621 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8622 QualType BaseTy = getType(LHSValue.Base);
8623 if (BaseTy->isIncompleteType())
8624 return Error(E);
8625 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8626 uint64_t OffsetLimit = Size.getQuantity();
8627 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8628 return Error(E);
8629 }
8630
Richard Smith8b3497e2011-10-31 01:37:14 +00008631 switch (E->getOpcode()) {
8632 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008633 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8634 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8635 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8636 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8637 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8638 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008639 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008640 }
8641 }
Richard Smith7bb00672012-02-01 01:42:44 +00008642
8643 if (LHSTy->isMemberPointerType()) {
8644 assert(E->isEqualityOp() && "unexpected member pointer operation");
8645 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8646
8647 MemberPtr LHSValue, RHSValue;
8648
8649 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008650 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008651 return false;
8652
8653 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8654 return false;
8655
8656 // C++11 [expr.eq]p2:
8657 // If both operands are null, they compare equal. Otherwise if only one is
8658 // null, they compare unequal.
8659 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8660 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8661 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8662 }
8663
8664 // Otherwise if either is a pointer to a virtual member function, the
8665 // result is unspecified.
8666 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8667 if (MD->isVirtual())
8668 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8669 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8670 if (MD->isVirtual())
8671 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8672
8673 // Otherwise they compare equal if and only if they would refer to the
8674 // same member of the same most derived object or the same subobject if
8675 // they were dereferenced with a hypothetical object of the associated
8676 // class type.
8677 bool Equal = LHSValue == RHSValue;
8678 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8679 }
8680
Richard Smithab44d9b2012-02-14 22:35:28 +00008681 if (LHSTy->isNullPtrType()) {
8682 assert(E->isComparisonOp() && "unexpected nullptr operation");
8683 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8684 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8685 // are compared, the result is true of the operator is <=, >= or ==, and
8686 // false otherwise.
8687 BinaryOperator::Opcode Opcode = E->getOpcode();
8688 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8689 }
8690
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008691 assert((!LHSTy->isIntegralOrEnumerationType() ||
8692 !RHSTy->isIntegralOrEnumerationType()) &&
8693 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8694 // We can't continue from here for non-integral types.
8695 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008696}
8697
Peter Collingbournee190dee2011-03-11 19:24:49 +00008698/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8699/// a result as the expression's type.
8700bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8701 const UnaryExprOrTypeTraitExpr *E) {
8702 switch(E->getKind()) {
8703 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008704 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008705 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008706 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008707 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008708 }
Eli Friedman64004332009-03-23 04:38:34 +00008709
Peter Collingbournee190dee2011-03-11 19:24:49 +00008710 case UETT_VecStep: {
8711 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008712
Peter Collingbournee190dee2011-03-11 19:24:49 +00008713 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008714 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008715
Peter Collingbournee190dee2011-03-11 19:24:49 +00008716 // The vec_step built-in functions that take a 3-component
8717 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8718 if (n == 3)
8719 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008720
Peter Collingbournee190dee2011-03-11 19:24:49 +00008721 return Success(n, E);
8722 } else
8723 return Success(1, E);
8724 }
8725
8726 case UETT_SizeOf: {
8727 QualType SrcTy = E->getTypeOfArgument();
8728 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8729 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008730 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8731 SrcTy = Ref->getPointeeType();
8732
Richard Smithd62306a2011-11-10 06:34:14 +00008733 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008734 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008735 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008736 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008737 }
Alexey Bataev00396512015-07-02 03:40:19 +00008738 case UETT_OpenMPRequiredSimdAlign:
8739 assert(E->isArgumentType());
8740 return Success(
8741 Info.Ctx.toCharUnitsFromBits(
8742 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8743 .getQuantity(),
8744 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008745 }
8746
8747 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008748}
8749
Peter Collingbournee9200682011-05-13 03:29:01 +00008750bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008751 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008752 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008753 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008754 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008755 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008756 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008757 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008758 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008759 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008760 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008761 APSInt IdxResult;
8762 if (!EvaluateInteger(Idx, IdxResult, Info))
8763 return false;
8764 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8765 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008766 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008767 CurrentType = AT->getElementType();
8768 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8769 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008770 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008771 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008772
James Y Knight7281c352015-12-29 22:31:18 +00008773 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008774 FieldDecl *MemberDecl = ON.getField();
8775 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008776 if (!RT)
8777 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008778 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008779 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008780 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008781 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008782 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008783 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008784 CurrentType = MemberDecl->getType().getNonReferenceType();
8785 break;
8786 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008787
James Y Knight7281c352015-12-29 22:31:18 +00008788 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008789 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008790
James Y Knight7281c352015-12-29 22:31:18 +00008791 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008792 CXXBaseSpecifier *BaseSpec = ON.getBase();
8793 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008794 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008795
8796 // Find the layout of the class whose base we are looking into.
8797 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008798 if (!RT)
8799 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008800 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008801 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008802 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8803
8804 // Find the base class itself.
8805 CurrentType = BaseSpec->getType();
8806 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8807 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008808 return Error(OOE);
Daniel Jasperffdee092017-05-02 19:21:42 +00008809
Douglas Gregord1702062010-04-29 00:18:15 +00008810 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008811 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008812 break;
8813 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008814 }
8815 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008816 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008817}
8818
Chris Lattnere13042c2008-07-11 19:10:17 +00008819bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008820 switch (E->getOpcode()) {
8821 default:
8822 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8823 // See C99 6.6p3.
8824 return Error(E);
8825 case UO_Extension:
8826 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8827 // If so, we could clear the diagnostic ID.
8828 return Visit(E->getSubExpr());
8829 case UO_Plus:
8830 // The result is just the value.
8831 return Visit(E->getSubExpr());
8832 case UO_Minus: {
8833 if (!Visit(E->getSubExpr()))
8834 return false;
8835 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008836 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008837 if (Value.isSigned() && Value.isMinSignedValue() &&
8838 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8839 E->getType()))
8840 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008841 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008842 }
8843 case UO_Not: {
8844 if (!Visit(E->getSubExpr()))
8845 return false;
8846 if (!Result.isInt()) return Error(E);
8847 return Success(~Result.getInt(), E);
8848 }
8849 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008850 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008851 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008852 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008853 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008854 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008855 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008856}
Mike Stump11289f42009-09-09 15:08:12 +00008857
Chris Lattner477c4be2008-07-12 01:15:53 +00008858/// HandleCast - This is used to evaluate implicit or explicit casts where the
8859/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008860bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8861 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008862 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008863 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008864
Eli Friedmanc757de22011-03-25 00:43:55 +00008865 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008866 case CK_BaseToDerived:
8867 case CK_DerivedToBase:
8868 case CK_UncheckedDerivedToBase:
8869 case CK_Dynamic:
8870 case CK_ToUnion:
8871 case CK_ArrayToPointerDecay:
8872 case CK_FunctionToPointerDecay:
8873 case CK_NullToPointer:
8874 case CK_NullToMemberPointer:
8875 case CK_BaseToDerivedMemberPointer:
8876 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008877 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008878 case CK_ConstructorConversion:
8879 case CK_IntegralToPointer:
8880 case CK_ToVoid:
8881 case CK_VectorSplat:
8882 case CK_IntegralToFloating:
8883 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008884 case CK_CPointerToObjCPointerCast:
8885 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008886 case CK_AnyPointerToBlockPointerCast:
8887 case CK_ObjCObjectLValueCast:
8888 case CK_FloatingRealToComplex:
8889 case CK_FloatingComplexToReal:
8890 case CK_FloatingComplexCast:
8891 case CK_FloatingComplexToIntegralComplex:
8892 case CK_IntegralRealToComplex:
8893 case CK_IntegralComplexCast:
8894 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008895 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008896 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008897 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008898 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008899 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008900 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008901 llvm_unreachable("invalid cast kind for integral value");
8902
Eli Friedman9faf2f92011-03-25 19:07:11 +00008903 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008904 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008905 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008906 case CK_ARCProduceObject:
8907 case CK_ARCConsumeObject:
8908 case CK_ARCReclaimReturnedObject:
8909 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008910 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008911 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008912
Richard Smith4ef685b2012-01-17 21:17:26 +00008913 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008914 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008915 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008916 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008917 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008918
8919 case CK_MemberPointerToBoolean:
8920 case CK_PointerToBoolean:
8921 case CK_IntegralToBoolean:
8922 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008923 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008924 case CK_FloatingComplexToBoolean:
8925 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008926 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008927 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008928 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008929 uint64_t IntResult = BoolResult;
8930 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8931 IntResult = (uint64_t)-1;
8932 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008933 }
8934
Eli Friedmanc757de22011-03-25 00:43:55 +00008935 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008936 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008937 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008938
Eli Friedman742421e2009-02-20 01:15:07 +00008939 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008940 // Allow casts of address-of-label differences if they are no-ops
8941 // or narrowing. (The narrowing case isn't actually guaranteed to
8942 // be constant-evaluatable except in some narrow cases which are hard
8943 // to detect here. We let it through on the assumption the user knows
8944 // what they are doing.)
8945 if (Result.isAddrLabelDiff())
8946 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008947 // Only allow casts of lvalues if they are lossless.
8948 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8949 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008950
Richard Smith911e1422012-01-30 22:27:01 +00008951 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8952 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008953 }
Mike Stump11289f42009-09-09 15:08:12 +00008954
Eli Friedmanc757de22011-03-25 00:43:55 +00008955 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008956 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8957
John McCall45d55e42010-05-07 21:00:08 +00008958 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008959 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008960 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008961
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008962 if (LV.getLValueBase()) {
8963 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008964 // FIXME: Allow a larger integer size than the pointer size, and allow
8965 // narrowing back down to pointer width in subsequent integral casts.
8966 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008967 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008968 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008969
Richard Smithcf74da72011-11-16 07:18:12 +00008970 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008971 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008972 return true;
8973 }
8974
Yaxun Liu402804b2016-12-15 08:09:08 +00008975 uint64_t V;
8976 if (LV.isNullPointer())
8977 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8978 else
8979 V = LV.getLValueOffset().getQuantity();
8980
8981 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008982 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008983 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008984
Eli Friedmanc757de22011-03-25 00:43:55 +00008985 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008986 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008987 if (!EvaluateComplex(SubExpr, C, Info))
8988 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008989 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008990 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008991
Eli Friedmanc757de22011-03-25 00:43:55 +00008992 case CK_FloatingToIntegral: {
8993 APFloat F(0.0);
8994 if (!EvaluateFloat(SubExpr, F, Info))
8995 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008996
Richard Smith357362d2011-12-13 06:39:58 +00008997 APSInt Value;
8998 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8999 return false;
9000 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009001 }
9002 }
Mike Stump11289f42009-09-09 15:08:12 +00009003
Eli Friedmanc757de22011-03-25 00:43:55 +00009004 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009005}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009006
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009007bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9008 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009009 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009010 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9011 return false;
9012 if (!LV.isComplexInt())
9013 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009014 return Success(LV.getComplexIntReal(), E);
9015 }
9016
9017 return Visit(E->getSubExpr());
9018}
9019
Eli Friedman4e7a2412009-02-27 04:45:43 +00009020bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009021 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009022 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009023 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9024 return false;
9025 if (!LV.isComplexInt())
9026 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009027 return Success(LV.getComplexIntImag(), E);
9028 }
9029
Richard Smith4a678122011-10-24 18:44:57 +00009030 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009031 return Success(0, E);
9032}
9033
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009034bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9035 return Success(E->getPackLength(), E);
9036}
9037
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009038bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9039 return Success(E->getValue(), E);
9040}
9041
Chris Lattner05706e882008-07-11 18:11:29 +00009042//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009043// Float Evaluation
9044//===----------------------------------------------------------------------===//
9045
9046namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009047class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009048 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009049 APFloat &Result;
9050public:
9051 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009052 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009053
Richard Smith2e312c82012-03-03 22:46:17 +00009054 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009055 Result = V.getFloat();
9056 return true;
9057 }
Eli Friedman24c01542008-08-22 00:06:13 +00009058
Richard Smithfddd3842011-12-30 21:15:51 +00009059 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009060 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9061 return true;
9062 }
9063
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009064 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009065
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009066 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009067 bool VisitBinaryOperator(const BinaryOperator *E);
9068 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009069 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009070
John McCallb1fb0d32010-05-07 22:08:54 +00009071 bool VisitUnaryReal(const UnaryOperator *E);
9072 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009073
Richard Smithfddd3842011-12-30 21:15:51 +00009074 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009075};
9076} // end anonymous namespace
9077
9078static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009079 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009080 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009081}
9082
Jay Foad39c79802011-01-12 09:06:06 +00009083static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009084 QualType ResultTy,
9085 const Expr *Arg,
9086 bool SNaN,
9087 llvm::APFloat &Result) {
9088 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9089 if (!S) return false;
9090
9091 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9092
9093 llvm::APInt fill;
9094
9095 // Treat empty strings as if they were zero.
9096 if (S->getString().empty())
9097 fill = llvm::APInt(32, 0);
9098 else if (S->getString().getAsInteger(0, fill))
9099 return false;
9100
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009101 if (Context.getTargetInfo().isNan2008()) {
9102 if (SNaN)
9103 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9104 else
9105 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9106 } else {
9107 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9108 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9109 // a different encoding to what became a standard in 2008, and for pre-
9110 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9111 // sNaN. This is now known as "legacy NaN" encoding.
9112 if (SNaN)
9113 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9114 else
9115 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9116 }
9117
John McCall16291492010-02-28 13:00:19 +00009118 return true;
9119}
9120
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009121bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009122 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009123 default:
9124 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9125
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009126 case Builtin::BI__builtin_huge_val:
9127 case Builtin::BI__builtin_huge_valf:
9128 case Builtin::BI__builtin_huge_vall:
9129 case Builtin::BI__builtin_inf:
9130 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009131 case Builtin::BI__builtin_infl: {
9132 const llvm::fltSemantics &Sem =
9133 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009134 Result = llvm::APFloat::getInf(Sem);
9135 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009136 }
Mike Stump11289f42009-09-09 15:08:12 +00009137
John McCall16291492010-02-28 13:00:19 +00009138 case Builtin::BI__builtin_nans:
9139 case Builtin::BI__builtin_nansf:
9140 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009141 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9142 true, Result))
9143 return Error(E);
9144 return true;
John McCall16291492010-02-28 13:00:19 +00009145
Chris Lattner0b7282e2008-10-06 06:31:58 +00009146 case Builtin::BI__builtin_nan:
9147 case Builtin::BI__builtin_nanf:
9148 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00009149 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009150 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009151 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9152 false, Result))
9153 return Error(E);
9154 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009155
9156 case Builtin::BI__builtin_fabs:
9157 case Builtin::BI__builtin_fabsf:
9158 case Builtin::BI__builtin_fabsl:
9159 if (!EvaluateFloat(E->getArg(0), Result, Info))
9160 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009161
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009162 if (Result.isNegative())
9163 Result.changeSign();
9164 return true;
9165
Richard Smith8889a3d2013-06-13 06:26:32 +00009166 // FIXME: Builtin::BI__builtin_powi
9167 // FIXME: Builtin::BI__builtin_powif
9168 // FIXME: Builtin::BI__builtin_powil
9169
Mike Stump11289f42009-09-09 15:08:12 +00009170 case Builtin::BI__builtin_copysign:
9171 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009172 case Builtin::BI__builtin_copysignl: {
9173 APFloat RHS(0.);
9174 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9175 !EvaluateFloat(E->getArg(1), RHS, Info))
9176 return false;
9177 Result.copySign(RHS);
9178 return true;
9179 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009180 }
9181}
9182
John McCallb1fb0d32010-05-07 22:08:54 +00009183bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009184 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9185 ComplexValue CV;
9186 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9187 return false;
9188 Result = CV.FloatReal;
9189 return true;
9190 }
9191
9192 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009193}
9194
9195bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009196 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9197 ComplexValue CV;
9198 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9199 return false;
9200 Result = CV.FloatImag;
9201 return true;
9202 }
9203
Richard Smith4a678122011-10-24 18:44:57 +00009204 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009205 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9206 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009207 return true;
9208}
9209
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009210bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009211 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009212 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009213 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009214 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009215 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009216 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9217 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009218 Result.changeSign();
9219 return true;
9220 }
9221}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009222
Eli Friedman24c01542008-08-22 00:06:13 +00009223bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009224 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9225 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009226
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009227 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009228 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009229 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009230 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009231 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9232 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009233}
9234
9235bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9236 Result = E->getValue();
9237 return true;
9238}
9239
Peter Collingbournee9200682011-05-13 03:29:01 +00009240bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9241 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009242
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009243 switch (E->getCastKind()) {
9244 default:
Richard Smith11562c52011-10-28 17:51:58 +00009245 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009246
9247 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009248 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009249 return EvaluateInteger(SubExpr, IntResult, Info) &&
9250 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9251 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009252 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009253
9254 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009255 if (!Visit(SubExpr))
9256 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009257 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9258 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009259 }
John McCalld7646252010-11-14 08:17:51 +00009260
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009261 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009262 ComplexValue V;
9263 if (!EvaluateComplex(SubExpr, V, Info))
9264 return false;
9265 Result = V.getComplexFloatReal();
9266 return true;
9267 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009268 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009269}
9270
Eli Friedman24c01542008-08-22 00:06:13 +00009271//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009272// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009273//===----------------------------------------------------------------------===//
9274
9275namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009276class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009277 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009278 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009279
Anders Carlsson537969c2008-11-16 20:27:53 +00009280public:
John McCall93d91dc2010-05-07 17:22:02 +00009281 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009282 : ExprEvaluatorBaseTy(info), Result(Result) {}
9283
Richard Smith2e312c82012-03-03 22:46:17 +00009284 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009285 Result.setFrom(V);
9286 return true;
9287 }
Mike Stump11289f42009-09-09 15:08:12 +00009288
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009289 bool ZeroInitialization(const Expr *E);
9290
Anders Carlsson537969c2008-11-16 20:27:53 +00009291 //===--------------------------------------------------------------------===//
9292 // Visitor Methods
9293 //===--------------------------------------------------------------------===//
9294
Peter Collingbournee9200682011-05-13 03:29:01 +00009295 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009296 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009297 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009298 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009299 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009300};
9301} // end anonymous namespace
9302
John McCall93d91dc2010-05-07 17:22:02 +00009303static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9304 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009305 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009306 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009307}
9308
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009309bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009310 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009311 if (ElemTy->isRealFloatingType()) {
9312 Result.makeComplexFloat();
9313 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9314 Result.FloatReal = Zero;
9315 Result.FloatImag = Zero;
9316 } else {
9317 Result.makeComplexInt();
9318 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9319 Result.IntReal = Zero;
9320 Result.IntImag = Zero;
9321 }
9322 return true;
9323}
9324
Peter Collingbournee9200682011-05-13 03:29:01 +00009325bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9326 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009327
9328 if (SubExpr->getType()->isRealFloatingType()) {
9329 Result.makeComplexFloat();
9330 APFloat &Imag = Result.FloatImag;
9331 if (!EvaluateFloat(SubExpr, Imag, Info))
9332 return false;
9333
9334 Result.FloatReal = APFloat(Imag.getSemantics());
9335 return true;
9336 } else {
9337 assert(SubExpr->getType()->isIntegerType() &&
9338 "Unexpected imaginary literal.");
9339
9340 Result.makeComplexInt();
9341 APSInt &Imag = Result.IntImag;
9342 if (!EvaluateInteger(SubExpr, Imag, Info))
9343 return false;
9344
9345 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9346 return true;
9347 }
9348}
9349
Peter Collingbournee9200682011-05-13 03:29:01 +00009350bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009351
John McCallfcef3cf2010-12-14 17:51:41 +00009352 switch (E->getCastKind()) {
9353 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009354 case CK_BaseToDerived:
9355 case CK_DerivedToBase:
9356 case CK_UncheckedDerivedToBase:
9357 case CK_Dynamic:
9358 case CK_ToUnion:
9359 case CK_ArrayToPointerDecay:
9360 case CK_FunctionToPointerDecay:
9361 case CK_NullToPointer:
9362 case CK_NullToMemberPointer:
9363 case CK_BaseToDerivedMemberPointer:
9364 case CK_DerivedToBaseMemberPointer:
9365 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009366 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009367 case CK_ConstructorConversion:
9368 case CK_IntegralToPointer:
9369 case CK_PointerToIntegral:
9370 case CK_PointerToBoolean:
9371 case CK_ToVoid:
9372 case CK_VectorSplat:
9373 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009374 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009375 case CK_IntegralToBoolean:
9376 case CK_IntegralToFloating:
9377 case CK_FloatingToIntegral:
9378 case CK_FloatingToBoolean:
9379 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009380 case CK_CPointerToObjCPointerCast:
9381 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009382 case CK_AnyPointerToBlockPointerCast:
9383 case CK_ObjCObjectLValueCast:
9384 case CK_FloatingComplexToReal:
9385 case CK_FloatingComplexToBoolean:
9386 case CK_IntegralComplexToReal:
9387 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009388 case CK_ARCProduceObject:
9389 case CK_ARCConsumeObject:
9390 case CK_ARCReclaimReturnedObject:
9391 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009392 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009393 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009394 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009395 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009396 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009397 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009398 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009399 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009400
John McCallfcef3cf2010-12-14 17:51:41 +00009401 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009402 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009403 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009404 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009405
9406 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009407 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009408 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009409 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009410
9411 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009412 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009413 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009414 return false;
9415
John McCallfcef3cf2010-12-14 17:51:41 +00009416 Result.makeComplexFloat();
9417 Result.FloatImag = APFloat(Real.getSemantics());
9418 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009419 }
9420
John McCallfcef3cf2010-12-14 17:51:41 +00009421 case CK_FloatingComplexCast: {
9422 if (!Visit(E->getSubExpr()))
9423 return false;
9424
9425 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9426 QualType From
9427 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9428
Richard Smith357362d2011-12-13 06:39:58 +00009429 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9430 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009431 }
9432
9433 case CK_FloatingComplexToIntegralComplex: {
9434 if (!Visit(E->getSubExpr()))
9435 return false;
9436
9437 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9438 QualType From
9439 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9440 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009441 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9442 To, Result.IntReal) &&
9443 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9444 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009445 }
9446
9447 case CK_IntegralRealToComplex: {
9448 APSInt &Real = Result.IntReal;
9449 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9450 return false;
9451
9452 Result.makeComplexInt();
9453 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9454 return true;
9455 }
9456
9457 case CK_IntegralComplexCast: {
9458 if (!Visit(E->getSubExpr()))
9459 return false;
9460
9461 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9462 QualType From
9463 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9464
Richard Smith911e1422012-01-30 22:27:01 +00009465 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9466 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009467 return true;
9468 }
9469
9470 case CK_IntegralComplexToFloatingComplex: {
9471 if (!Visit(E->getSubExpr()))
9472 return false;
9473
Ted Kremenek28831752012-08-23 20:46:57 +00009474 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009475 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009476 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009477 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009478 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9479 To, Result.FloatReal) &&
9480 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9481 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009482 }
9483 }
9484
9485 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009486}
9487
John McCall93d91dc2010-05-07 17:22:02 +00009488bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009489 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009490 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9491
Chandler Carrutha216cad2014-10-11 00:57:18 +00009492 // Track whether the LHS or RHS is real at the type system level. When this is
9493 // the case we can simplify our evaluation strategy.
9494 bool LHSReal = false, RHSReal = false;
9495
9496 bool LHSOK;
9497 if (E->getLHS()->getType()->isRealFloatingType()) {
9498 LHSReal = true;
9499 APFloat &Real = Result.FloatReal;
9500 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9501 if (LHSOK) {
9502 Result.makeComplexFloat();
9503 Result.FloatImag = APFloat(Real.getSemantics());
9504 }
9505 } else {
9506 LHSOK = Visit(E->getLHS());
9507 }
George Burgess IVa145e252016-05-25 22:38:36 +00009508 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009509 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009510
John McCall93d91dc2010-05-07 17:22:02 +00009511 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009512 if (E->getRHS()->getType()->isRealFloatingType()) {
9513 RHSReal = true;
9514 APFloat &Real = RHS.FloatReal;
9515 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9516 return false;
9517 RHS.makeComplexFloat();
9518 RHS.FloatImag = APFloat(Real.getSemantics());
9519 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009520 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009521
Chandler Carrutha216cad2014-10-11 00:57:18 +00009522 assert(!(LHSReal && RHSReal) &&
9523 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009524 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009525 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009526 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009527 if (Result.isComplexFloat()) {
9528 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9529 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009530 if (LHSReal)
9531 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9532 else if (!RHSReal)
9533 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9534 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009535 } else {
9536 Result.getComplexIntReal() += RHS.getComplexIntReal();
9537 Result.getComplexIntImag() += RHS.getComplexIntImag();
9538 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009539 break;
John McCalle3027922010-08-25 11:45:40 +00009540 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009541 if (Result.isComplexFloat()) {
9542 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9543 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009544 if (LHSReal) {
9545 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9546 Result.getComplexFloatImag().changeSign();
9547 } else if (!RHSReal) {
9548 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9549 APFloat::rmNearestTiesToEven);
9550 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009551 } else {
9552 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9553 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9554 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009555 break;
John McCalle3027922010-08-25 11:45:40 +00009556 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009557 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009558 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009559 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009560 // following naming scheme:
9561 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009562 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009563 APFloat &A = LHS.getComplexFloatReal();
9564 APFloat &B = LHS.getComplexFloatImag();
9565 APFloat &C = RHS.getComplexFloatReal();
9566 APFloat &D = RHS.getComplexFloatImag();
9567 APFloat &ResR = Result.getComplexFloatReal();
9568 APFloat &ResI = Result.getComplexFloatImag();
9569 if (LHSReal) {
9570 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9571 ResR = A * C;
9572 ResI = A * D;
9573 } else if (RHSReal) {
9574 ResR = C * A;
9575 ResI = C * B;
9576 } else {
9577 // In the fully general case, we need to handle NaNs and infinities
9578 // robustly.
9579 APFloat AC = A * C;
9580 APFloat BD = B * D;
9581 APFloat AD = A * D;
9582 APFloat BC = B * C;
9583 ResR = AC - BD;
9584 ResI = AD + BC;
9585 if (ResR.isNaN() && ResI.isNaN()) {
9586 bool Recalc = false;
9587 if (A.isInfinity() || B.isInfinity()) {
9588 A = APFloat::copySign(
9589 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9590 B = APFloat::copySign(
9591 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9592 if (C.isNaN())
9593 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9594 if (D.isNaN())
9595 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9596 Recalc = true;
9597 }
9598 if (C.isInfinity() || D.isInfinity()) {
9599 C = APFloat::copySign(
9600 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9601 D = APFloat::copySign(
9602 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9603 if (A.isNaN())
9604 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9605 if (B.isNaN())
9606 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9607 Recalc = true;
9608 }
9609 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9610 AD.isInfinity() || BC.isInfinity())) {
9611 if (A.isNaN())
9612 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9613 if (B.isNaN())
9614 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9615 if (C.isNaN())
9616 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9617 if (D.isNaN())
9618 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9619 Recalc = true;
9620 }
9621 if (Recalc) {
9622 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9623 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9624 }
9625 }
9626 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009627 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009628 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009629 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009630 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9631 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009632 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009633 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9634 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9635 }
9636 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009637 case BO_Div:
9638 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009639 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009640 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009641 // following naming scheme:
9642 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009643 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009644 APFloat &A = LHS.getComplexFloatReal();
9645 APFloat &B = LHS.getComplexFloatImag();
9646 APFloat &C = RHS.getComplexFloatReal();
9647 APFloat &D = RHS.getComplexFloatImag();
9648 APFloat &ResR = Result.getComplexFloatReal();
9649 APFloat &ResI = Result.getComplexFloatImag();
9650 if (RHSReal) {
9651 ResR = A / C;
9652 ResI = B / C;
9653 } else {
9654 if (LHSReal) {
9655 // No real optimizations we can do here, stub out with zero.
9656 B = APFloat::getZero(A.getSemantics());
9657 }
9658 int DenomLogB = 0;
9659 APFloat MaxCD = maxnum(abs(C), abs(D));
9660 if (MaxCD.isFinite()) {
9661 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009662 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9663 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009664 }
9665 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009666 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9667 APFloat::rmNearestTiesToEven);
9668 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9669 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009670 if (ResR.isNaN() && ResI.isNaN()) {
9671 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9672 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9673 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9674 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9675 D.isFinite()) {
9676 A = APFloat::copySign(
9677 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9678 B = APFloat::copySign(
9679 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9680 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9681 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9682 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9683 C = APFloat::copySign(
9684 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9685 D = APFloat::copySign(
9686 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9687 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9688 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9689 }
9690 }
9691 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009692 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009693 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9694 return Error(E, diag::note_expr_divide_by_zero);
9695
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009696 ComplexValue LHS = Result;
9697 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9698 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9699 Result.getComplexIntReal() =
9700 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9701 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9702 Result.getComplexIntImag() =
9703 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9704 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9705 }
9706 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009707 }
9708
John McCall93d91dc2010-05-07 17:22:02 +00009709 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009710}
9711
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009712bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9713 // Get the operand value into 'Result'.
9714 if (!Visit(E->getSubExpr()))
9715 return false;
9716
9717 switch (E->getOpcode()) {
9718 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009719 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009720 case UO_Extension:
9721 return true;
9722 case UO_Plus:
9723 // The result is always just the subexpr.
9724 return true;
9725 case UO_Minus:
9726 if (Result.isComplexFloat()) {
9727 Result.getComplexFloatReal().changeSign();
9728 Result.getComplexFloatImag().changeSign();
9729 }
9730 else {
9731 Result.getComplexIntReal() = -Result.getComplexIntReal();
9732 Result.getComplexIntImag() = -Result.getComplexIntImag();
9733 }
9734 return true;
9735 case UO_Not:
9736 if (Result.isComplexFloat())
9737 Result.getComplexFloatImag().changeSign();
9738 else
9739 Result.getComplexIntImag() = -Result.getComplexIntImag();
9740 return true;
9741 }
9742}
9743
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009744bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9745 if (E->getNumInits() == 2) {
9746 if (E->getType()->isComplexType()) {
9747 Result.makeComplexFloat();
9748 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9749 return false;
9750 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9751 return false;
9752 } else {
9753 Result.makeComplexInt();
9754 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9755 return false;
9756 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9757 return false;
9758 }
9759 return true;
9760 }
9761 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9762}
9763
Anders Carlsson537969c2008-11-16 20:27:53 +00009764//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009765// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9766// implicit conversion.
9767//===----------------------------------------------------------------------===//
9768
9769namespace {
9770class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009771 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009772 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +00009773 APValue &Result;
9774public:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009775 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9776 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +00009777
9778 bool Success(const APValue &V, const Expr *E) {
9779 Result = V;
9780 return true;
9781 }
9782
9783 bool ZeroInitialization(const Expr *E) {
9784 ImplicitValueInitExpr VIE(
9785 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009786 // For atomic-qualified class (and array) types in C++, initialize the
9787 // _Atomic-wrapped subobject directly, in-place.
9788 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9789 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +00009790 }
9791
9792 bool VisitCastExpr(const CastExpr *E) {
9793 switch (E->getCastKind()) {
9794 default:
9795 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9796 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009797 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9798 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +00009799 }
9800 }
9801};
9802} // end anonymous namespace
9803
Richard Smith64cb9ca2017-02-22 22:09:50 +00009804static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9805 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +00009806 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009807 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +00009808}
9809
9810//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009811// Void expression evaluation, primarily for a cast to void on the LHS of a
9812// comma operator
9813//===----------------------------------------------------------------------===//
9814
9815namespace {
9816class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009817 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009818public:
9819 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9820
Richard Smith2e312c82012-03-03 22:46:17 +00009821 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009822
Richard Smith7cd577b2017-08-17 19:35:50 +00009823 bool ZeroInitialization(const Expr *E) { return true; }
9824
Richard Smith42d3af92011-12-07 00:43:50 +00009825 bool VisitCastExpr(const CastExpr *E) {
9826 switch (E->getCastKind()) {
9827 default:
9828 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9829 case CK_ToVoid:
9830 VisitIgnoredValue(E->getSubExpr());
9831 return true;
9832 }
9833 }
Hal Finkela8443c32014-07-17 14:49:58 +00009834
9835 bool VisitCallExpr(const CallExpr *E) {
9836 switch (E->getBuiltinCallee()) {
9837 default:
9838 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9839 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009840 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009841 // The argument is not evaluated!
9842 return true;
9843 }
9844 }
Richard Smith42d3af92011-12-07 00:43:50 +00009845};
9846} // end anonymous namespace
9847
9848static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9849 assert(E->isRValue() && E->getType()->isVoidType());
9850 return VoidExprEvaluator(Info).Visit(E);
9851}
9852
9853//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009854// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009855//===----------------------------------------------------------------------===//
9856
Richard Smith2e312c82012-03-03 22:46:17 +00009857static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009858 // In C, function designators are not lvalues, but we evaluate them as if they
9859 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009860 QualType T = E->getType();
9861 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009862 LValue LV;
9863 if (!EvaluateLValue(E, LV, Info))
9864 return false;
9865 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009866 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009867 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009868 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009869 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009870 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009871 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009872 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009873 LValue LV;
9874 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009875 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009876 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009877 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009878 llvm::APFloat F(0.0);
9879 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009880 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009881 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009882 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009883 ComplexValue C;
9884 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009885 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009886 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009887 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009888 MemberPtr P;
9889 if (!EvaluateMemberPointer(E, P, Info))
9890 return false;
9891 P.moveInto(Result);
9892 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009893 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009894 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009895 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009896 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9897 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009898 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009899 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009900 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009901 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009902 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009903 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9904 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009905 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009906 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009907 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009908 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009909 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009910 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009911 if (!EvaluateVoid(E, Info))
9912 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009913 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009914 QualType Unqual = T.getAtomicUnqualifiedType();
9915 if (Unqual->isArrayType() || Unqual->isRecordType()) {
9916 LValue LV;
9917 LV.set(E, Info.CurrentCall->Index);
9918 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9919 if (!EvaluateAtomic(E, &LV, Value, Info))
9920 return false;
9921 } else {
9922 if (!EvaluateAtomic(E, nullptr, Result, Info))
9923 return false;
9924 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009925 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009926 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009927 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009928 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009929 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009930 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009931 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009932
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009933 return true;
9934}
9935
Richard Smithb228a862012-02-15 02:18:13 +00009936/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9937/// cases, the in-place evaluation is essential, since later initializers for
9938/// an object can indirectly refer to subobjects which were initialized earlier.
9939static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009940 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009941 assert(!E->isValueDependent());
9942
Richard Smith7525ff62013-05-09 07:14:00 +00009943 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009944 return false;
9945
9946 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009947 // Evaluate arrays and record types in-place, so that later initializers can
9948 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +00009949 QualType T = E->getType();
9950 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +00009951 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00009952 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +00009953 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00009954 else if (T->isAtomicType()) {
9955 QualType Unqual = T.getAtomicUnqualifiedType();
9956 if (Unqual->isArrayType() || Unqual->isRecordType())
9957 return EvaluateAtomic(E, &This, Result, Info);
9958 }
Richard Smithed5165f2011-11-04 05:33:44 +00009959 }
9960
9961 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009962 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009963}
9964
Richard Smithf57d8cb2011-12-09 22:58:01 +00009965/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9966/// lvalue-to-rvalue cast if it is an lvalue.
9967static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009968 if (E->getType().isNull())
9969 return false;
9970
Nick Lewyckyc190f962017-05-02 01:06:16 +00009971 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +00009972 return false;
9973
Richard Smith2e312c82012-03-03 22:46:17 +00009974 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009975 return false;
9976
9977 if (E->isGLValue()) {
9978 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009979 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009980 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009981 return false;
9982 }
9983
Richard Smith2e312c82012-03-03 22:46:17 +00009984 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009985 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009986}
Richard Smith11562c52011-10-28 17:51:58 +00009987
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009988static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +00009989 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009990 // Fast-path evaluations of integer literals, since we sometimes see files
9991 // containing vast quantities of these.
9992 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9993 Result.Val = APValue(APSInt(L->getValue(),
9994 L->getType()->isUnsignedIntegerType()));
9995 IsConst = true;
9996 return true;
9997 }
James Dennett0492ef02014-03-14 17:44:10 +00009998
9999 // This case should be rare, but we need to check it before we check on
10000 // the type below.
10001 if (Exp->getType().isNull()) {
10002 IsConst = false;
10003 return true;
10004 }
Daniel Jasperffdee092017-05-02 19:21:42 +000010005
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010006 // FIXME: Evaluating values of large array and record types can cause
10007 // performance problems. Only do so in C++11 for now.
10008 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10009 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010010 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010011 IsConst = false;
10012 return true;
10013 }
10014 return false;
10015}
10016
10017
Richard Smith7b553f12011-10-29 00:50:52 +000010018/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010019/// any crazy technique (that has nothing to do with language standards) that
10020/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010021/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10022/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +000010023bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010024 bool IsConst;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010025 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010026 return IsConst;
Daniel Jasperffdee092017-05-02 19:21:42 +000010027
Richard Smith6d4c6582013-11-05 22:18:15 +000010028 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010029 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +000010030}
10031
Jay Foad39c79802011-01-12 09:06:06 +000010032bool Expr::EvaluateAsBooleanCondition(bool &Result,
10033 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010034 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010035 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010036 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010037}
10038
Richard Smithce8eca52015-12-08 03:21:47 +000010039static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10040 Expr::SideEffectsKind SEK) {
10041 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10042 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10043}
10044
Richard Smith5fab0c92011-12-28 19:48:30 +000010045bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10046 SideEffectsKind AllowSideEffects) const {
10047 if (!getType()->isIntegralOrEnumerationType())
10048 return false;
10049
Richard Smith11562c52011-10-28 17:51:58 +000010050 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010051 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +000010052 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010053 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010054
Richard Smith11562c52011-10-28 17:51:58 +000010055 Result = ExprResult.Val.getInt();
10056 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010057}
10058
Richard Trieube234c32016-04-21 21:04:55 +000010059bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10060 SideEffectsKind AllowSideEffects) const {
10061 if (!getType()->isRealFloatingType())
10062 return false;
10063
10064 EvalResult ExprResult;
10065 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10066 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10067 return false;
10068
10069 Result = ExprResult.Val.getFloat();
10070 return true;
10071}
10072
Jay Foad39c79802011-01-12 09:06:06 +000010073bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010074 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010075
John McCall45d55e42010-05-07 21:00:08 +000010076 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010077 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10078 !CheckLValueConstantExpression(Info, getExprLoc(),
10079 Ctx.getLValueReferenceType(getType()), LV))
10080 return false;
10081
Richard Smith2e312c82012-03-03 22:46:17 +000010082 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010083 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010084}
10085
Richard Smithd0b4dd62011-12-19 06:19:21 +000010086bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10087 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010088 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010089 // FIXME: Evaluating initializers for large array and record types can cause
10090 // performance problems. Only do so in C++11 for now.
10091 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010092 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010093 return false;
10094
Richard Smithd0b4dd62011-12-19 06:19:21 +000010095 Expr::EvalStatus EStatus;
10096 EStatus.Diag = &Notes;
10097
Richard Smith0c6124b2015-12-03 01:36:22 +000010098 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10099 ? EvalInfo::EM_ConstantExpression
10100 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010101 InitInfo.setEvaluatingDecl(VD, Value);
10102
10103 LValue LVal;
10104 LVal.set(VD);
10105
Richard Smithfddd3842011-12-30 21:15:51 +000010106 // C++11 [basic.start.init]p2:
10107 // Variables with static storage duration or thread storage duration shall be
10108 // zero-initialized before any other initialization takes place.
10109 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010110 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010111 !VD->getType()->isReferenceType()) {
10112 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010113 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010114 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010115 return false;
10116 }
10117
Richard Smith7525ff62013-05-09 07:14:00 +000010118 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10119 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010120 EStatus.HasSideEffects)
10121 return false;
10122
10123 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10124 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010125}
10126
Richard Smith7b553f12011-10-29 00:50:52 +000010127/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10128/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010129bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010130 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010131 return EvaluateAsRValue(Result, Ctx) &&
10132 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010133}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010134
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010135APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010136 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010137 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010138 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010139 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010140 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010141 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010142 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010143
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010144 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010145}
John McCall864e3962010-05-07 05:32:02 +000010146
Richard Smithe9ff7702013-11-05 22:23:30 +000010147void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010148 bool IsConst;
10149 EvalResult EvalResult;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010150 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010151 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010152 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10153 }
10154}
10155
Richard Smithe6c01442013-06-05 00:46:14 +000010156bool Expr::EvalResult::isGlobalLValue() const {
10157 assert(Val.isLValue());
10158 return IsGlobalLValue(Val.getLValueBase());
10159}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010160
10161
John McCall864e3962010-05-07 05:32:02 +000010162/// isIntegerConstantExpr - this recursive routine will test if an expression is
10163/// an integer constant expression.
10164
10165/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10166/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010167
10168// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010169// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10170// and a (possibly null) SourceLocation indicating the location of the problem.
10171//
John McCall864e3962010-05-07 05:32:02 +000010172// Note that to reduce code duplication, this helper does no evaluation
10173// itself; the caller checks whether the expression is evaluatable, and
10174// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010175// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010176
Dan Gohman28ade552010-07-26 21:25:24 +000010177namespace {
10178
Richard Smith9e575da2012-12-28 13:25:52 +000010179enum ICEKind {
10180 /// This expression is an ICE.
10181 IK_ICE,
10182 /// This expression is not an ICE, but if it isn't evaluated, it's
10183 /// a legal subexpression for an ICE. This return value is used to handle
10184 /// the comma operator in C99 mode, and non-constant subexpressions.
10185 IK_ICEIfUnevaluated,
10186 /// This expression is not an ICE, and is not a legal subexpression for one.
10187 IK_NotICE
10188};
10189
John McCall864e3962010-05-07 05:32:02 +000010190struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010191 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010192 SourceLocation Loc;
10193
Richard Smith9e575da2012-12-28 13:25:52 +000010194 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010195};
10196
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010197}
Dan Gohman28ade552010-07-26 21:25:24 +000010198
Richard Smith9e575da2012-12-28 13:25:52 +000010199static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10200
10201static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010202
Craig Toppera31a8822013-08-22 07:09:37 +000010203static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010204 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010205 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010206 !EVResult.Val.isInt())
10207 return ICEDiag(IK_NotICE, E->getLocStart());
10208
John McCall864e3962010-05-07 05:32:02 +000010209 return NoDiag();
10210}
10211
Craig Toppera31a8822013-08-22 07:09:37 +000010212static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010213 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010214 if (!E->getType()->isIntegralOrEnumerationType())
10215 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010216
10217 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010218#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010219#define STMT(Node, Base) case Expr::Node##Class:
10220#define EXPR(Node, Base)
10221#include "clang/AST/StmtNodes.inc"
10222 case Expr::PredefinedExprClass:
10223 case Expr::FloatingLiteralClass:
10224 case Expr::ImaginaryLiteralClass:
10225 case Expr::StringLiteralClass:
10226 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010227 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010228 case Expr::MemberExprClass:
10229 case Expr::CompoundAssignOperatorClass:
10230 case Expr::CompoundLiteralExprClass:
10231 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010232 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010233 case Expr::ArrayInitLoopExprClass:
10234 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010235 case Expr::NoInitExprClass:
10236 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010237 case Expr::ImplicitValueInitExprClass:
10238 case Expr::ParenListExprClass:
10239 case Expr::VAArgExprClass:
10240 case Expr::AddrLabelExprClass:
10241 case Expr::StmtExprClass:
10242 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010243 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010244 case Expr::CXXDynamicCastExprClass:
10245 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010246 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010247 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010248 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010249 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010250 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010251 case Expr::CXXThisExprClass:
10252 case Expr::CXXThrowExprClass:
10253 case Expr::CXXNewExprClass:
10254 case Expr::CXXDeleteExprClass:
10255 case Expr::CXXPseudoDestructorExprClass:
10256 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010257 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010258 case Expr::DependentScopeDeclRefExprClass:
10259 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010260 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010261 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010262 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010263 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010264 case Expr::CXXTemporaryObjectExprClass:
10265 case Expr::CXXUnresolvedConstructExprClass:
10266 case Expr::CXXDependentScopeMemberExprClass:
10267 case Expr::UnresolvedMemberExprClass:
10268 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010269 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010270 case Expr::ObjCArrayLiteralClass:
10271 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010272 case Expr::ObjCEncodeExprClass:
10273 case Expr::ObjCMessageExprClass:
10274 case Expr::ObjCSelectorExprClass:
10275 case Expr::ObjCProtocolExprClass:
10276 case Expr::ObjCIvarRefExprClass:
10277 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010278 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010279 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010280 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010281 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010282 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010283 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010284 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010285 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010286 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010287 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010288 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010289 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010290 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010291 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010292 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010293 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010294 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010295 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010296 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000010297 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010298 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010299 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010300
Richard Smithf137f932014-01-25 20:50:08 +000010301 case Expr::InitListExprClass: {
10302 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10303 // form "T x = { a };" is equivalent to "T x = a;".
10304 // Unless we're initializing a reference, T is a scalar as it is known to be
10305 // of integral or enumeration type.
10306 if (E->isRValue())
10307 if (cast<InitListExpr>(E)->getNumInits() == 1)
10308 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10309 return ICEDiag(IK_NotICE, E->getLocStart());
10310 }
10311
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010312 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010313 case Expr::GNUNullExprClass:
10314 // GCC considers the GNU __null value to be an integral constant expression.
10315 return NoDiag();
10316
John McCall7c454bb2011-07-15 05:09:51 +000010317 case Expr::SubstNonTypeTemplateParmExprClass:
10318 return
10319 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10320
John McCall864e3962010-05-07 05:32:02 +000010321 case Expr::ParenExprClass:
10322 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010323 case Expr::GenericSelectionExprClass:
10324 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010325 case Expr::IntegerLiteralClass:
10326 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010327 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010328 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010329 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010330 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010331 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010332 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010333 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010334 return NoDiag();
10335 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010336 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010337 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10338 // constant expressions, but they can never be ICEs because an ICE cannot
10339 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010340 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010341 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010342 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010343 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010344 }
Richard Smith6365c912012-02-24 22:12:32 +000010345 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010346 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10347 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010348 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010349 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010350 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010351 // Parameter variables are never constants. Without this check,
10352 // getAnyInitializer() can find a default argument, which leads
10353 // to chaos.
10354 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010355 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010356
10357 // C++ 7.1.5.1p2
10358 // A variable of non-volatile const-qualified integral or enumeration
10359 // type initialized by an ICE can be used in ICEs.
10360 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010361 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010362 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010363
Richard Smithd0b4dd62011-12-19 06:19:21 +000010364 const VarDecl *VD;
10365 // Look for a declaration of this variable that has an initializer, and
10366 // check whether it is an ICE.
10367 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10368 return NoDiag();
10369 else
Richard Smith9e575da2012-12-28 13:25:52 +000010370 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010371 }
10372 }
Richard Smith9e575da2012-12-28 13:25:52 +000010373 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010374 }
John McCall864e3962010-05-07 05:32:02 +000010375 case Expr::UnaryOperatorClass: {
10376 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10377 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010378 case UO_PostInc:
10379 case UO_PostDec:
10380 case UO_PreInc:
10381 case UO_PreDec:
10382 case UO_AddrOf:
10383 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010384 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010385 // C99 6.6/3 allows increment and decrement within unevaluated
10386 // subexpressions of constant expressions, but they can never be ICEs
10387 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010388 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010389 case UO_Extension:
10390 case UO_LNot:
10391 case UO_Plus:
10392 case UO_Minus:
10393 case UO_Not:
10394 case UO_Real:
10395 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010396 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010397 }
Richard Smith9e575da2012-12-28 13:25:52 +000010398
John McCall864e3962010-05-07 05:32:02 +000010399 // OffsetOf falls through here.
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010400 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010401 }
10402 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010403 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10404 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10405 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10406 // compliance: we should warn earlier for offsetof expressions with
10407 // array subscripts that aren't ICEs, and if the array subscripts
10408 // are ICEs, the value of the offsetof must be an integer constant.
10409 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010410 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010411 case Expr::UnaryExprOrTypeTraitExprClass: {
10412 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10413 if ((Exp->getKind() == UETT_SizeOf) &&
10414 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010415 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010416 return NoDiag();
10417 }
10418 case Expr::BinaryOperatorClass: {
10419 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10420 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010421 case BO_PtrMemD:
10422 case BO_PtrMemI:
10423 case BO_Assign:
10424 case BO_MulAssign:
10425 case BO_DivAssign:
10426 case BO_RemAssign:
10427 case BO_AddAssign:
10428 case BO_SubAssign:
10429 case BO_ShlAssign:
10430 case BO_ShrAssign:
10431 case BO_AndAssign:
10432 case BO_XorAssign:
10433 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000010434 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10435 // constant expressions, but they can never be ICEs because an ICE cannot
10436 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010437 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010438
John McCalle3027922010-08-25 11:45:40 +000010439 case BO_Mul:
10440 case BO_Div:
10441 case BO_Rem:
10442 case BO_Add:
10443 case BO_Sub:
10444 case BO_Shl:
10445 case BO_Shr:
10446 case BO_LT:
10447 case BO_GT:
10448 case BO_LE:
10449 case BO_GE:
10450 case BO_EQ:
10451 case BO_NE:
10452 case BO_And:
10453 case BO_Xor:
10454 case BO_Or:
10455 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010456 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10457 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010458 if (Exp->getOpcode() == BO_Div ||
10459 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010460 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010461 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010462 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010463 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010464 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010465 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010466 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010467 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010468 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010469 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010470 }
10471 }
10472 }
John McCalle3027922010-08-25 11:45:40 +000010473 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010474 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010475 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10476 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010477 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10478 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010479 } else {
10480 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010481 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010482 }
10483 }
Richard Smith9e575da2012-12-28 13:25:52 +000010484 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010485 }
John McCalle3027922010-08-25 11:45:40 +000010486 case BO_LAnd:
10487 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010488 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10489 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010490 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010491 // Rare case where the RHS has a comma "side-effect"; we need
10492 // to actually check the condition to see whether the side
10493 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010494 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010495 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010496 return RHSResult;
10497 return NoDiag();
10498 }
10499
Richard Smith9e575da2012-12-28 13:25:52 +000010500 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010501 }
10502 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010503 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010504 }
10505 case Expr::ImplicitCastExprClass:
10506 case Expr::CStyleCastExprClass:
10507 case Expr::CXXFunctionalCastExprClass:
10508 case Expr::CXXStaticCastExprClass:
10509 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010510 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010511 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010512 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010513 if (isa<ExplicitCastExpr>(E)) {
10514 if (const FloatingLiteral *FL
10515 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10516 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10517 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10518 APSInt IgnoredVal(DestWidth, !DestSigned);
10519 bool Ignored;
10520 // If the value does not fit in the destination type, the behavior is
10521 // undefined, so we are not required to treat it as a constant
10522 // expression.
10523 if (FL->getValue().convertToInteger(IgnoredVal,
10524 llvm::APFloat::rmTowardZero,
10525 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010526 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010527 return NoDiag();
10528 }
10529 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010530 switch (cast<CastExpr>(E)->getCastKind()) {
10531 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010532 case CK_AtomicToNonAtomic:
10533 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010534 case CK_NoOp:
10535 case CK_IntegralToBoolean:
10536 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010537 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010538 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010539 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010540 }
John McCall864e3962010-05-07 05:32:02 +000010541 }
John McCallc07a0c72011-02-17 10:25:35 +000010542 case Expr::BinaryConditionalOperatorClass: {
10543 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10544 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010545 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010546 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010547 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10548 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10549 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010550 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010551 return FalseResult;
10552 }
John McCall864e3962010-05-07 05:32:02 +000010553 case Expr::ConditionalOperatorClass: {
10554 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10555 // If the condition (ignoring parens) is a __builtin_constant_p call,
10556 // then only the true side is actually considered in an integer constant
10557 // expression, and it is fully evaluated. This is an important GNU
10558 // extension. See GCC PR38377 for discussion.
10559 if (const CallExpr *CallCE
10560 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010561 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010562 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010563 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010564 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010565 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010566
Richard Smithf57d8cb2011-12-09 22:58:01 +000010567 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10568 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010569
Richard Smith9e575da2012-12-28 13:25:52 +000010570 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010571 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010572 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010573 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010574 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010575 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010576 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010577 return NoDiag();
10578 // Rare case where the diagnostics depend on which side is evaluated
10579 // Note that if we get here, CondResult is 0, and at least one of
10580 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010581 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010582 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010583 return TrueResult;
10584 }
10585 case Expr::CXXDefaultArgExprClass:
10586 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010587 case Expr::CXXDefaultInitExprClass:
10588 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010589 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010590 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010591 }
10592 }
10593
David Blaikiee4d798f2012-01-20 21:50:17 +000010594 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010595}
10596
Richard Smithf57d8cb2011-12-09 22:58:01 +000010597/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010598static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010599 const Expr *E,
10600 llvm::APSInt *Value,
10601 SourceLocation *Loc) {
10602 if (!E->getType()->isIntegralOrEnumerationType()) {
10603 if (Loc) *Loc = E->getExprLoc();
10604 return false;
10605 }
10606
Richard Smith66e05fe2012-01-18 05:21:49 +000010607 APValue Result;
10608 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010609 return false;
10610
Richard Smith98710fc2014-11-13 23:03:19 +000010611 if (!Result.isInt()) {
10612 if (Loc) *Loc = E->getExprLoc();
10613 return false;
10614 }
10615
Richard Smith66e05fe2012-01-18 05:21:49 +000010616 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010617 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010618}
10619
Craig Toppera31a8822013-08-22 07:09:37 +000010620bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10621 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010622 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010623 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010624
Richard Smith9e575da2012-12-28 13:25:52 +000010625 ICEDiag D = CheckICE(this, Ctx);
10626 if (D.Kind != IK_ICE) {
10627 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010628 return false;
10629 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010630 return true;
10631}
10632
Craig Toppera31a8822013-08-22 07:09:37 +000010633bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010634 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010635 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010636 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10637
10638 if (!isIntegerConstantExpr(Ctx, Loc))
10639 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010640 // The only possible side-effects here are due to UB discovered in the
10641 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10642 // required to treat the expression as an ICE, so we produce the folded
10643 // value.
10644 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010645 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010646 return true;
10647}
Richard Smith66e05fe2012-01-18 05:21:49 +000010648
Craig Toppera31a8822013-08-22 07:09:37 +000010649bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010650 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010651}
10652
Craig Toppera31a8822013-08-22 07:09:37 +000010653bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010654 SourceLocation *Loc) const {
10655 // We support this checking in C++98 mode in order to diagnose compatibility
10656 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010657 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010658
Richard Smith98a0a492012-02-14 21:38:30 +000010659 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010660 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010661 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010662 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010663 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010664
10665 APValue Scratch;
10666 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10667
10668 if (!Diags.empty()) {
10669 IsConstExpr = false;
10670 if (Loc) *Loc = Diags[0].first;
10671 } else if (!IsConstExpr) {
10672 // FIXME: This shouldn't happen.
10673 if (Loc) *Loc = getExprLoc();
10674 }
10675
10676 return IsConstExpr;
10677}
Richard Smith253c2a32012-01-27 01:14:48 +000010678
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010679bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10680 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010681 ArrayRef<const Expr*> Args,
10682 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010683 Expr::EvalStatus Status;
10684 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10685
George Burgess IV177399e2017-01-09 04:12:14 +000010686 LValue ThisVal;
10687 const LValue *ThisPtr = nullptr;
10688 if (This) {
10689#ifndef NDEBUG
10690 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10691 assert(MD && "Don't provide `this` for non-methods.");
10692 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10693#endif
10694 if (EvaluateObjectArgument(Info, This, ThisVal))
10695 ThisPtr = &ThisVal;
10696 if (Info.EvalStatus.HasSideEffects)
10697 return false;
10698 }
10699
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010700 ArgVector ArgValues(Args.size());
10701 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10702 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010703 if ((*I)->isValueDependent() ||
10704 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010705 // If evaluation fails, throw away the argument entirely.
10706 ArgValues[I - Args.begin()] = APValue();
10707 if (Info.EvalStatus.HasSideEffects)
10708 return false;
10709 }
10710
10711 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010712 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010713 ArgValues.data());
10714 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10715}
10716
Richard Smith253c2a32012-01-27 01:14:48 +000010717bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010718 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010719 PartialDiagnosticAt> &Diags) {
10720 // FIXME: It would be useful to check constexpr function templates, but at the
10721 // moment the constant expression evaluator cannot cope with the non-rigorous
10722 // ASTs which we build for dependent expressions.
10723 if (FD->isDependentContext())
10724 return true;
10725
10726 Expr::EvalStatus Status;
10727 Status.Diag = &Diags;
10728
Richard Smith6d4c6582013-11-05 22:18:15 +000010729 EvalInfo Info(FD->getASTContext(), Status,
10730 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010731
10732 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010733 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010734
Richard Smith7525ff62013-05-09 07:14:00 +000010735 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010736 // is a temporary being used as the 'this' pointer.
10737 LValue This;
10738 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010739 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010740
Richard Smith253c2a32012-01-27 01:14:48 +000010741 ArrayRef<const Expr*> Args;
10742
Richard Smith2e312c82012-03-03 22:46:17 +000010743 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010744 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10745 // Evaluate the call as a constant initializer, to allow the construction
10746 // of objects of non-literal types.
10747 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010748 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10749 } else {
10750 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010751 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010752 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010753 }
Richard Smith253c2a32012-01-27 01:14:48 +000010754
10755 return Diags.empty();
10756}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010757
10758bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10759 const FunctionDecl *FD,
10760 SmallVectorImpl<
10761 PartialDiagnosticAt> &Diags) {
10762 Expr::EvalStatus Status;
10763 Status.Diag = &Diags;
10764
10765 EvalInfo Info(FD->getASTContext(), Status,
10766 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10767
10768 // Fabricate a call stack frame to give the arguments a plausible cover story.
10769 ArrayRef<const Expr*> Args;
10770 ArgVector ArgValues(0);
10771 bool Success = EvaluateArgs(Args, ArgValues, Info);
10772 (void)Success;
10773 assert(Success &&
10774 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010775 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010776
10777 APValue ResultScratch;
10778 Evaluate(ResultScratch, Info, E);
10779 return Diags.empty();
10780}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010781
10782bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10783 unsigned Type) const {
10784 if (!getType()->isPointerType())
10785 return false;
10786
10787 Expr::EvalStatus Status;
10788 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010789 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010790}