blob: 11e753c07713a347464c8288889ec35e25cfce18 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anders Carlsson7a241ba2008-07-03 04:20:39 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
Richard Smith253c2a32012-01-27 01:14:48 +000011// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000025// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000027//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000033//===----------------------------------------------------------------------===//
34
35#include "clang/AST/APValue.h"
36#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000037#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000038#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Tim Northover314fbfa2018-11-02 13:14:11 +000041#include "clang/AST/OSLog.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"
Leonard Chand3f3e162019-01-18 21:04:25 +000046#include "clang/Basic/FixedPoint.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000047#include "clang/Basic/TargetInfo.h"
Fangrui Song407659a2018-11-30 23:41:18 +000048#include "llvm/Support/SaveAndRestore.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000049#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000050#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000051#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000052
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000053#define DEBUG_TYPE "exprconstant"
54
Anders Carlsson7a241ba2008-07-03 04:20:39 +000055using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000056using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000057using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000058
Richard Smithb228a862012-02-15 02:18:13 +000059static bool IsGlobalLValue(APValue::LValueBase B);
60
John McCall93d91dc2010-05-07 17:22:02 +000061namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000062 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000063 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000064 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000065
Richard Smithb228a862012-02-15 02:18:13 +000066 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000067 if (!B) return QualType();
Richard Smith69cf59e2018-03-09 02:00:01 +000068 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000069 // FIXME: It's unclear where we're supposed to take the type from, and
Richard Smith69cf59e2018-03-09 02:00:01 +000070 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000071 //
72 // extern int arr[]; void f() { extern int arr[3]; };
73 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000074 //
75 // For now, we take the array bound from the most recent declaration.
76 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
77 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
78 QualType T = Redecl->getType();
79 if (!T->isIncompleteArrayType())
80 return T;
81 }
82 return D->getType();
83 }
Richard Smith84401042013-06-03 05:03:02 +000084
85 const Expr *Base = B.get<const Expr*>();
86
87 // For a materialized temporary, the type of the temporary we materialized
88 // may not be the type of the expression.
89 if (const MaterializeTemporaryExpr *MTE =
90 dyn_cast<MaterializeTemporaryExpr>(Base)) {
91 SmallVector<const Expr *, 2> CommaLHSs;
92 SmallVector<SubobjectAdjustment, 2> Adjustments;
93 const Expr *Temp = MTE->GetTemporaryExpr();
94 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
95 Adjustments);
96 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000097 // for it directly. Otherwise use the type after adjustment.
98 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000099 return Inner->getType();
100 }
101
102 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000103 }
104
Richard Smithd62306a2011-11-10 06:34:14 +0000105 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000106 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +0000107 static
Richard Smith84f6dcf2012-02-02 01:16:57 +0000108 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +0000109 APValue::BaseOrMemberType Value;
110 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +0000111 return Value;
112 }
113
114 /// Get an LValue path entry, which is known to not be an array index, as a
115 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000116 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000117 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000118 }
119 /// Get an LValue path entry, which is known to not be an array index, as a
120 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000121 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000122 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000123 }
124 /// Determine whether this LValue path entry for a base class names a virtual
125 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000126 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000127 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000128 }
129
George Burgess IVe3763372016-12-22 02:50:20 +0000130 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
131 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
132 const FunctionDecl *Callee = CE->getDirectCallee();
133 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
134 }
135
136 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
137 /// This will look through a single cast.
138 ///
139 /// Returns null if we couldn't unwrap a function with alloc_size.
140 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
141 if (!E->getType()->isPointerType())
142 return nullptr;
143
144 E = E->IgnoreParens();
145 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000146 // probably be a cast of some kind. In exotic cases, we might also see a
147 // top-level ExprWithCleanups. Ignore them either way.
Bill Wendling7c44da22018-10-31 03:48:47 +0000148 if (const auto *FE = dyn_cast<FullExpr>(E))
149 E = FE->getSubExpr()->IgnoreParens();
George Burgess IV47638762018-03-07 04:52:34 +0000150
George Burgess IVe3763372016-12-22 02:50:20 +0000151 if (const auto *Cast = dyn_cast<CastExpr>(E))
152 E = Cast->getSubExpr()->IgnoreParens();
153
154 if (const auto *CE = dyn_cast<CallExpr>(E))
155 return getAllocSizeAttr(CE) ? CE : nullptr;
156 return nullptr;
157 }
158
159 /// Determines whether or not the given Base contains a call to a function
160 /// with the alloc_size attribute.
161 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
162 const auto *E = Base.dyn_cast<const Expr *>();
163 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
164 }
165
Richard Smith6f4f0f12017-10-20 22:56:25 +0000166 /// The bound to claim that an array of unknown bound has.
167 /// The value in MostDerivedArraySize is undefined in this case. So, set it
168 /// to an arbitrary value that's likely to loudly break things if it's used.
169 static const uint64_t AssumedSizeForUnsizedArray =
170 std::numeric_limits<uint64_t>::max() / 2;
171
George Burgess IVe3763372016-12-22 02:50:20 +0000172 /// Determines if an LValue with the given LValueBase will have an unsized
173 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000174 /// Find the path length and type of the most-derived subobject in the given
175 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000176 static unsigned
177 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
178 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000179 uint64_t &ArraySize, QualType &Type, bool &IsArray,
180 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000181 // This only accepts LValueBases from APValues, and APValues don't support
182 // arrays that lack size info.
183 assert(!isBaseAnAllocSizeCall(Base) &&
184 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000185 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000186 Type = getType(Base);
187
Richard Smith80815602011-11-07 05:07:52 +0000188 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000189 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000190 const ArrayType *AT = Ctx.getAsArrayType(Type);
191 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000192 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000193 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000194
195 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
196 ArraySize = CAT->getSize().getZExtValue();
197 } else {
198 assert(I == 0 && "unexpected unsized array designator");
199 FirstEntryIsUnsizedArray = true;
200 ArraySize = AssumedSizeForUnsizedArray;
201 }
Richard Smith66c96992012-02-18 22:04:06 +0000202 } else if (Type->isAnyComplexType()) {
203 const ComplexType *CT = Type->castAs<ComplexType>();
204 Type = CT->getElementType();
205 ArraySize = 2;
206 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000207 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000208 } else if (const FieldDecl *FD = getAsField(Path[I])) {
209 Type = FD->getType();
210 ArraySize = 0;
211 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000212 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000213 } else {
Richard Smith80815602011-11-07 05:07:52 +0000214 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000215 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000216 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000217 }
Richard Smith80815602011-11-07 05:07:52 +0000218 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000219 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000220 }
221
Richard Smitha8105bc2012-01-06 16:39:00 +0000222 // The order of this enum is important for diagnostics.
223 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000224 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000225 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000226 };
227
Richard Smith96e0c102011-11-04 02:25:55 +0000228 /// A path from a glvalue to a subobject of that glvalue.
229 struct SubobjectDesignator {
230 /// True if the subobject was named in a manner not supported by C++11. Such
231 /// lvalues can still be folded, but they are not core constant expressions
232 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000233 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000234
Richard Smitha8105bc2012-01-06 16:39:00 +0000235 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000236 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000237
Daniel Jasperffdee092017-05-02 19:21:42 +0000238 /// Indicator of whether the first entry is an unsized array.
239 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000240
George Burgess IVa51c4072015-10-16 01:49:01 +0000241 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000242 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000243
Richard Smitha8105bc2012-01-06 16:39:00 +0000244 /// The length of the path to the most-derived object of which this is a
245 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000246 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000247
George Burgess IVa51c4072015-10-16 01:49:01 +0000248 /// The size of the array of which the most-derived object is an element.
249 /// This will always be 0 if the most-derived object is not an array
250 /// element. 0 is not an indicator of whether or not the most-derived object
251 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000252 ///
253 /// If the current array is an unsized array, the value of this is
254 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000255 uint64_t MostDerivedArraySize;
256
257 /// The type of the most derived object referred to by this address.
258 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000259
Richard Smith80815602011-11-07 05:07:52 +0000260 typedef APValue::LValuePathEntry PathEntry;
261
Richard Smith96e0c102011-11-04 02:25:55 +0000262 /// The entries on the path from the glvalue to the designated subobject.
263 SmallVector<PathEntry, 8> Entries;
264
Richard Smitha8105bc2012-01-06 16:39:00 +0000265 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000266
Richard Smitha8105bc2012-01-06 16:39:00 +0000267 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000268 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000269 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000270 MostDerivedPathLength(0), MostDerivedArraySize(0),
271 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000272
273 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000274 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000275 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000276 MostDerivedPathLength(0), MostDerivedArraySize(0) {
277 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000278 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000279 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000280 ArrayRef<PathEntry> VEntries = V.getLValuePath();
281 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000282 if (V.getLValueBase()) {
283 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000284 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000285 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000286 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000287 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000288 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000289 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000290 }
Richard Smith80815602011-11-07 05:07:52 +0000291 }
292 }
293
Richard Smith96e0c102011-11-04 02:25:55 +0000294 void setInvalid() {
295 Invalid = true;
296 Entries.clear();
297 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000298
George Burgess IVe3763372016-12-22 02:50:20 +0000299 /// Determine whether the most derived subobject is an array without a
300 /// known bound.
301 bool isMostDerivedAnUnsizedArray() const {
302 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000303 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000304 }
305
306 /// Determine what the most derived array's size is. Results in an assertion
307 /// failure if the most derived array lacks a size.
308 uint64_t getMostDerivedArraySize() const {
309 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
310 return MostDerivedArraySize;
311 }
312
Richard Smitha8105bc2012-01-06 16:39:00 +0000313 /// Determine whether this is a one-past-the-end pointer.
314 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000315 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000316 if (IsOnePastTheEnd)
317 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000318 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000319 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
320 return true;
321 return false;
322 }
323
Richard Smith06f71b52018-08-04 00:57:17 +0000324 /// Get the range of valid index adjustments in the form
325 /// {maximum value that can be subtracted from this pointer,
326 /// maximum value that can be added to this pointer}
327 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
328 if (Invalid || isMostDerivedAnUnsizedArray())
329 return {0, 0};
330
331 // [expr.add]p4: For the purposes of these operators, a pointer to a
332 // nonarray object behaves the same as a pointer to the first element of
333 // an array of length one with the type of the object as its element type.
334 bool IsArray = MostDerivedPathLength == Entries.size() &&
335 MostDerivedIsArrayElement;
336 uint64_t ArrayIndex =
337 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
338 uint64_t ArraySize =
339 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
340 return {ArrayIndex, ArraySize - ArrayIndex};
341 }
342
Richard Smitha8105bc2012-01-06 16:39:00 +0000343 /// Check that this refers to a valid subobject.
344 bool isValidSubobject() const {
345 if (Invalid)
346 return false;
347 return !isOnePastTheEnd();
348 }
349 /// Check that this refers to a valid subobject, and if not, produce a
350 /// relevant diagnostic and set the designator as invalid.
351 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
352
Richard Smith06f71b52018-08-04 00:57:17 +0000353 /// Get the type of the designated object.
354 QualType getType(ASTContext &Ctx) const {
355 assert(!Invalid && "invalid designator has no subobject type");
356 return MostDerivedPathLength == Entries.size()
357 ? MostDerivedType
358 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
359 }
360
Richard Smitha8105bc2012-01-06 16:39:00 +0000361 /// Update this designator to refer to the first element within this array.
362 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000363 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000364 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000365 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000366
367 // This is a most-derived object.
368 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000369 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000370 MostDerivedArraySize = CAT->getSize().getZExtValue();
371 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000372 }
George Burgess IVe3763372016-12-22 02:50:20 +0000373 /// Update this designator to refer to the first element within the array of
374 /// elements of type T. This is an array of unknown size.
375 void addUnsizedArrayUnchecked(QualType ElemTy) {
376 PathEntry Entry;
377 Entry.ArrayIndex = 0;
378 Entries.push_back(Entry);
379
380 MostDerivedType = ElemTy;
381 MostDerivedIsArrayElement = true;
382 // The value in MostDerivedArraySize is undefined in this case. So, set it
383 // to an arbitrary value that's likely to loudly break things if it's
384 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000385 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000386 MostDerivedPathLength = Entries.size();
387 }
Richard Smith96e0c102011-11-04 02:25:55 +0000388 /// Update this designator to refer to the given base or member of this
389 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000390 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000391 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000392 APValue::BaseOrMemberType Value(D, Virtual);
393 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000394 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000395
396 // If this isn't a base class, it's a new most-derived object.
397 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
398 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000399 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000400 MostDerivedArraySize = 0;
401 MostDerivedPathLength = Entries.size();
402 }
Richard Smith96e0c102011-11-04 02:25:55 +0000403 }
Richard Smith66c96992012-02-18 22:04:06 +0000404 /// Update this designator to refer to the given complex component.
405 void addComplexUnchecked(QualType EltTy, bool Imag) {
406 PathEntry Entry;
407 Entry.ArrayIndex = Imag;
408 Entries.push_back(Entry);
409
410 // This is technically a most-derived object, though in practice this
411 // is unlikely to matter.
412 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000413 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000414 MostDerivedArraySize = 2;
415 MostDerivedPathLength = Entries.size();
416 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000417 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000418 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
419 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000420 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000421 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
422 if (Invalid || !N) return;
423 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
424 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000425 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000426 // Can't verify -- trust that the user is doing the right thing (or if
427 // not, trust that the caller will catch the bad behavior).
428 // FIXME: Should we reject if this overflows, at least?
429 Entries.back().ArrayIndex += TruncatedN;
430 return;
431 }
432
433 // [expr.add]p4: For the purposes of these operators, a pointer to a
434 // nonarray object behaves the same as a pointer to the first element of
435 // an array of length one with the type of the object as its element type.
436 bool IsArray = MostDerivedPathLength == Entries.size() &&
437 MostDerivedIsArrayElement;
438 uint64_t ArrayIndex =
439 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
440 uint64_t ArraySize =
441 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
442
443 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
444 // Calculate the actual index in a wide enough type, so we can include
445 // it in the note.
446 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
447 (llvm::APInt&)N += ArrayIndex;
448 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
449 diagnosePointerArithmetic(Info, E, N);
450 setInvalid();
451 return;
452 }
453
454 ArrayIndex += TruncatedN;
455 assert(ArrayIndex <= ArraySize &&
456 "bounds check succeeded for out-of-bounds index");
457
458 if (IsArray)
459 Entries.back().ArrayIndex = ArrayIndex;
460 else
461 IsOnePastTheEnd = (ArrayIndex != 0);
462 }
Richard Smith96e0c102011-11-04 02:25:55 +0000463 };
464
Richard Smith254a73d2011-10-28 22:34:42 +0000465 /// A stack frame in the constexpr call stack.
466 struct CallStackFrame {
467 EvalInfo &Info;
468
469 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000470 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000471
Richard Smithf6f003a2011-12-16 19:06:07 +0000472 /// Callee - The function which was called.
473 const FunctionDecl *Callee;
474
Richard Smithd62306a2011-11-10 06:34:14 +0000475 /// This - The binding for the this pointer in this call, if any.
476 const LValue *This;
477
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000478 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000479 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000480 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000481
Eli Friedman4830ec82012-06-25 21:21:08 +0000482 // Note that we intentionally use std::map here so that references to
483 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000484 typedef std::pair<const void *, unsigned> MapKeyTy;
485 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000486 /// Temporaries - Temporary lvalues materialized within this stack frame.
487 MapTy Temporaries;
488
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000489 /// CallLoc - The location of the call expression for this call.
490 SourceLocation CallLoc;
491
492 /// Index - The call index of this call.
493 unsigned Index;
494
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000495 /// The stack of integers for tracking version numbers for temporaries.
496 SmallVector<unsigned, 2> TempVersionStack = {1};
497 unsigned CurTempVersion = TempVersionStack.back();
498
499 unsigned getTempVersion() const { return TempVersionStack.back(); }
500
501 void pushTempVersion() {
502 TempVersionStack.push_back(++CurTempVersion);
503 }
504
505 void popTempVersion() {
506 TempVersionStack.pop_back();
507 }
508
Faisal Vali051e3a22017-02-16 04:12:21 +0000509 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000510 // on the overall stack usage of deeply-recursing constexpr evaluations.
Faisal Vali051e3a22017-02-16 04:12:21 +0000511 // (We should cache this map rather than recomputing it repeatedly.)
512 // But let's try this and see how it goes; we can look into caching the map
513 // as a later change.
514
515 /// LambdaCaptureFields - Mapping from captured variables/this to
516 /// corresponding data members in the closure class.
517 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
518 FieldDecl *LambdaThisCaptureField;
519
Richard Smithf6f003a2011-12-16 19:06:07 +0000520 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
521 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000522 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000523 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000524
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000525 // Return the temporary for Key whose version number is Version.
526 APValue *getTemporary(const void *Key, unsigned Version) {
527 MapKeyTy KV(Key, Version);
528 auto LB = Temporaries.lower_bound(KV);
529 if (LB != Temporaries.end() && LB->first == KV)
530 return &LB->second;
531 // Pair (Key,Version) wasn't found in the map. Check that no elements
532 // in the map have 'Key' as their key.
533 assert((LB == Temporaries.end() || LB->first.first != Key) &&
534 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
535 "Element with key 'Key' found in map");
536 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000537 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000538
539 // Return the current temporary for Key in the map.
540 APValue *getCurrentTemporary(const void *Key) {
541 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
542 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
543 return &std::prev(UB)->second;
544 return nullptr;
545 }
546
547 // Return the version number of the current temporary for Key.
548 unsigned getCurrentTemporaryVersion(const void *Key) const {
549 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
550 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
551 return std::prev(UB)->first.second;
552 return 0;
553 }
554
Richard Smith08d6a2c2013-07-24 07:11:57 +0000555 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000556 };
557
Richard Smith852c9db2013-04-20 22:23:05 +0000558 /// Temporarily override 'this'.
559 class ThisOverrideRAII {
560 public:
561 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
562 : Frame(Frame), OldThis(Frame.This) {
563 if (Enable)
564 Frame.This = NewThis;
565 }
566 ~ThisOverrideRAII() {
567 Frame.This = OldThis;
568 }
569 private:
570 CallStackFrame &Frame;
571 const LValue *OldThis;
572 };
573
Richard Smith92b1ce02011-12-12 09:28:41 +0000574 /// A partial diagnostic which we might know in advance that we are not going
575 /// to emit.
576 class OptionalDiagnostic {
577 PartialDiagnostic *Diag;
578
579 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000580 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
581 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000582
583 template<typename T>
584 OptionalDiagnostic &operator<<(const T &v) {
585 if (Diag)
586 *Diag << v;
587 return *this;
588 }
Richard Smithfe800032012-01-31 04:08:20 +0000589
590 OptionalDiagnostic &operator<<(const APSInt &I) {
591 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000592 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000593 I.toString(Buffer);
594 *Diag << StringRef(Buffer.data(), Buffer.size());
595 }
596 return *this;
597 }
598
599 OptionalDiagnostic &operator<<(const APFloat &F) {
600 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000601 // FIXME: Force the precision of the source value down so we don't
602 // print digits which are usually useless (we don't really care here if
603 // we truncate a digit by accident in edge cases). Ideally,
Fangrui Song6907ce22018-07-30 19:24:48 +0000604 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000605 // representation which rounds to the correct value, but it's a bit
606 // tricky to implement.
607 unsigned precision =
608 llvm::APFloat::semanticsPrecision(F.getSemantics());
609 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000610 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000611 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000612 *Diag << StringRef(Buffer.data(), Buffer.size());
613 }
614 return *this;
615 }
Leonard Chand3f3e162019-01-18 21:04:25 +0000616
617 OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
618 if (Diag) {
619 SmallVector<char, 32> Buffer;
620 FX.toString(Buffer);
621 *Diag << StringRef(Buffer.data(), Buffer.size());
622 }
623 return *this;
624 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000625 };
626
Richard Smith08d6a2c2013-07-24 07:11:57 +0000627 /// A cleanup, and a flag indicating whether it is lifetime-extended.
628 class Cleanup {
629 llvm::PointerIntPair<APValue*, 1, bool> Value;
630
631 public:
632 Cleanup(APValue *Val, bool IsLifetimeExtended)
633 : Value(Val, IsLifetimeExtended) {}
634
635 bool isLifetimeExtended() const { return Value.getInt(); }
636 void endLifetime() {
637 *Value.getPointer() = APValue();
638 }
639 };
640
Richard Smithb228a862012-02-15 02:18:13 +0000641 /// EvalInfo - This is a private struct used by the evaluator to capture
642 /// information about a subexpression as it is folded. It retains information
643 /// about the AST context, but also maintains information about the folded
644 /// expression.
645 ///
646 /// If an expression could be evaluated, it is still possible it is not a C
647 /// "integer constant expression" or constant expression. If not, this struct
648 /// captures information about how and why not.
649 ///
650 /// One bit of information passed *into* the request for constant folding
651 /// indicates whether the subexpression is "evaluated" or not according to C
652 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
653 /// evaluate the expression regardless of what the RHS is, but C only allows
654 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000655 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000656 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000657
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000658 /// EvalStatus - Contains information about the evaluation.
659 Expr::EvalStatus &EvalStatus;
660
661 /// CurrentCall - The top of the constexpr call stack.
662 CallStackFrame *CurrentCall;
663
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000664 /// CallStackDepth - The number of calls in the call stack right now.
665 unsigned CallStackDepth;
666
Richard Smithb228a862012-02-15 02:18:13 +0000667 /// NextCallIndex - The next call index to assign.
668 unsigned NextCallIndex;
669
Richard Smitha3d3bd22013-05-08 02:12:03 +0000670 /// StepsLeft - The remaining number of evaluation steps we're permitted
671 /// to perform. This is essentially a limit for the number of statements
672 /// we will evaluate.
673 unsigned StepsLeft;
674
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000675 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000676 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000677 CallStackFrame BottomFrame;
678
Richard Smith08d6a2c2013-07-24 07:11:57 +0000679 /// A stack of values whose lifetimes end at the end of some surrounding
680 /// evaluation frame.
681 llvm::SmallVector<Cleanup, 16> CleanupStack;
682
Richard Smithd62306a2011-11-10 06:34:14 +0000683 /// EvaluatingDecl - This is the declaration whose initializer is being
684 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000685 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000686
687 /// EvaluatingDeclValue - This is the value being constructed for the
688 /// declaration whose initializer is being evaluated, if any.
689 APValue *EvaluatingDeclValue;
690
Erik Pilkington42925492017-10-04 00:18:55 +0000691 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
692 /// the call index that that lvalue was allocated in.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000693 typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
694 EvaluatingObject;
Erik Pilkington42925492017-10-04 00:18:55 +0000695
696 /// EvaluatingConstructors - Set of objects that are currently being
697 /// constructed.
698 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
699
700 struct EvaluatingConstructorRAII {
701 EvalInfo &EI;
702 EvaluatingObject Object;
703 bool DidInsert;
704 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
705 : EI(EI), Object(Object) {
706 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
707 }
708 ~EvaluatingConstructorRAII() {
709 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
710 }
711 };
712
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000713 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
714 unsigned Version) {
715 return EvaluatingConstructors.count(
716 EvaluatingObject(Decl, {CallIndex, Version}));
Erik Pilkington42925492017-10-04 00:18:55 +0000717 }
718
Richard Smith37be3362019-05-04 04:00:45 +0000719 /// If we're currently speculatively evaluating, the outermost call stack
720 /// depth at which we can mutate state, otherwise 0.
721 unsigned SpeculativeEvaluationDepth = 0;
722
Richard Smith410306b2016-12-12 02:53:20 +0000723 /// The current array initialization index, if we're performing array
724 /// initialization.
725 uint64_t ArrayInitIndex = -1;
726
Richard Smith357362d2011-12-13 06:39:58 +0000727 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
728 /// notes attached to it will also be stored, otherwise they will not be.
729 bool HasActiveDiagnostic;
730
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000731 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000732 /// fold (not just why it's not strictly a constant expression)?
733 bool HasFoldFailureDiagnostic;
734
Fangrui Song407659a2018-11-30 23:41:18 +0000735 /// Whether or not we're in a context where the front end requires a
736 /// constant value.
737 bool InConstantContext;
738
Richard Smith6d4c6582013-11-05 22:18:15 +0000739 enum EvaluationMode {
740 /// Evaluate as a constant expression. Stop if we find that the expression
741 /// is not a constant expression.
742 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000743
Richard Smith6d4c6582013-11-05 22:18:15 +0000744 /// Evaluate as a potential constant expression. Keep going if we hit a
745 /// construct that we can't evaluate yet (because we don't yet know the
746 /// value of something) but stop if we hit something that could never be
747 /// a constant expression.
748 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000749
Richard Smith6d4c6582013-11-05 22:18:15 +0000750 /// Fold the expression to a constant. Stop if we hit a side-effect that
751 /// we can't model.
752 EM_ConstantFold,
753
754 /// Evaluate the expression looking for integer overflow and similar
755 /// issues. Don't worry about side-effects, and try to visit all
756 /// subexpressions.
757 EM_EvaluateForOverflow,
758
759 /// Evaluate in any way we know how. Don't worry about side-effects that
760 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000761 EM_IgnoreSideEffects,
762
763 /// Evaluate as a constant expression. Stop if we find that the expression
764 /// is not a constant expression. Some expressions can be retried in the
765 /// optimizer if we don't constant fold them here, but in an unevaluated
766 /// context we try to fold them immediately since the optimizer never
767 /// gets a chance to look at it.
768 EM_ConstantExpressionUnevaluated,
769
770 /// Evaluate as a potential constant expression. Keep going if we hit a
771 /// construct that we can't evaluate yet (because we don't yet know the
772 /// value of something) but stop if we hit something that could never be
773 /// a constant expression. Some expressions can be retried in the
774 /// optimizer if we don't constant fold them here, but in an unevaluated
775 /// context we try to fold them immediately since the optimizer never
776 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000777 EM_PotentialConstantExpressionUnevaluated,
Richard Smith6d4c6582013-11-05 22:18:15 +0000778 } EvalMode;
779
780 /// Are we checking whether the expression is a potential constant
781 /// expression?
782 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000783 return EvalMode == EM_PotentialConstantExpression ||
784 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000785 }
786
787 /// Are we checking an expression for overflow?
788 // FIXME: We should check for any kind of undefined or suspicious behavior
789 // in such constructs, not just overflow.
790 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
791
792 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000793 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000794 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000795 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000796 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
797 EvaluatingDecl((const ValueDecl *)nullptr),
798 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
Richard Smith37be3362019-05-04 04:00:45 +0000799 HasFoldFailureDiagnostic(false),
Fangrui Song407659a2018-11-30 23:41:18 +0000800 InConstantContext(false), EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000801
Richard Smith7525ff62013-05-09 07:14:00 +0000802 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
803 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000804 EvaluatingDeclValue = &Value;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000805 EvaluatingConstructors.insert({Base, {0, 0}});
Richard Smithd62306a2011-11-10 06:34:14 +0000806 }
807
David Blaikiebbafb8a2012-03-11 07:00:24 +0000808 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000809
Richard Smith357362d2011-12-13 06:39:58 +0000810 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000811 // Don't perform any constexpr calls (other than the call we're checking)
812 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000813 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000814 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000815 if (NextCallIndex == 0) {
816 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000817 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000818 return false;
819 }
Richard Smith357362d2011-12-13 06:39:58 +0000820 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
821 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000822 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000823 << getLangOpts().ConstexprCallDepth;
824 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000825 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000826
Richard Smith37be3362019-05-04 04:00:45 +0000827 std::pair<CallStackFrame *, unsigned>
828 getCallFrameAndDepth(unsigned CallIndex) {
829 assert(CallIndex && "no call index in getCallFrameAndDepth");
Richard Smithb228a862012-02-15 02:18:13 +0000830 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
831 // be null in this loop.
Richard Smith37be3362019-05-04 04:00:45 +0000832 unsigned Depth = CallStackDepth;
Richard Smithb228a862012-02-15 02:18:13 +0000833 CallStackFrame *Frame = CurrentCall;
Richard Smith37be3362019-05-04 04:00:45 +0000834 while (Frame->Index > CallIndex) {
Richard Smithb228a862012-02-15 02:18:13 +0000835 Frame = Frame->Caller;
Richard Smith37be3362019-05-04 04:00:45 +0000836 --Depth;
837 }
838 if (Frame->Index == CallIndex)
839 return {Frame, Depth};
840 return {nullptr, 0};
Richard Smithb228a862012-02-15 02:18:13 +0000841 }
842
Richard Smitha3d3bd22013-05-08 02:12:03 +0000843 bool nextStep(const Stmt *S) {
844 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000845 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000846 return false;
847 }
848 --StepsLeft;
849 return true;
850 }
851
Richard Smith357362d2011-12-13 06:39:58 +0000852 private:
853 /// Add a diagnostic to the diagnostics list.
854 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
855 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
856 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
857 return EvalStatus.Diag->back().second;
858 }
859
Richard Smithf6f003a2011-12-16 19:06:07 +0000860 /// Add notes containing a call stack to the current point of evaluation.
861 void addCallStack(unsigned Limit);
862
Faisal Valie690b7a2016-07-02 22:34:24 +0000863 private:
864 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
865 unsigned ExtraNotes, bool IsCCEDiag) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000866
Richard Smith92b1ce02011-12-12 09:28:41 +0000867 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000868 // If we have a prior diagnostic, it will be noting that the expression
869 // isn't a constant expression. This diagnostic is more important,
870 // unless we require this evaluation to produce a constant expression.
871 //
872 // FIXME: We might want to show both diagnostics to the user in
873 // EM_ConstantFold mode.
874 if (!EvalStatus.Diag->empty()) {
875 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000876 case EM_ConstantFold:
877 case EM_IgnoreSideEffects:
878 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000879 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000880 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000881 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000882 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000883 case EM_ConstantExpression:
884 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000885 case EM_ConstantExpressionUnevaluated:
886 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000887 HasActiveDiagnostic = false;
888 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000889 }
890 }
891
Richard Smithf6f003a2011-12-16 19:06:07 +0000892 unsigned CallStackNotes = CallStackDepth - 1;
893 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
894 if (Limit)
895 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000896 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000897 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000898
Richard Smith357362d2011-12-13 06:39:58 +0000899 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000900 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000901 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000902 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
903 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000904 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000905 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000906 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000907 }
Richard Smith357362d2011-12-13 06:39:58 +0000908 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000909 return OptionalDiagnostic();
910 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000911 public:
912 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
913 OptionalDiagnostic
914 FFDiag(SourceLocation Loc,
915 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
916 unsigned ExtraNotes = 0) {
917 return Diag(Loc, DiagId, ExtraNotes, false);
918 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000919
Faisal Valie690b7a2016-07-02 22:34:24 +0000920 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000921 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000922 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000923 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000924 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000925 HasActiveDiagnostic = false;
926 return OptionalDiagnostic();
927 }
928
Richard Smith92b1ce02011-12-12 09:28:41 +0000929 /// Diagnose that the evaluation does not produce a C++11 core constant
930 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000931 ///
932 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
933 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000934 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000935 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000936 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000937 // Don't override a previous diagnostic. Don't bother collecting
938 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000939 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000940 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000941 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000942 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000943 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000944 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000945 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
946 = diag::note_invalid_subexpr_in_const_expr,
947 unsigned ExtraNotes = 0) {
948 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
949 }
Richard Smith357362d2011-12-13 06:39:58 +0000950 /// Add a note to a prior diagnostic.
951 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
952 if (!HasActiveDiagnostic)
953 return OptionalDiagnostic();
954 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000955 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000956
957 /// Add a stack of notes to a prior diagnostic.
958 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
959 if (HasActiveDiagnostic) {
960 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
961 Diags.begin(), Diags.end());
962 }
963 }
Richard Smith253c2a32012-01-27 01:14:48 +0000964
Richard Smith6d4c6582013-11-05 22:18:15 +0000965 /// Should we continue evaluation after encountering a side-effect that we
966 /// couldn't model?
967 bool keepEvaluatingAfterSideEffect() {
968 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000969 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000970 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000971 case EM_EvaluateForOverflow:
972 case EM_IgnoreSideEffects:
973 return true;
974
Richard Smith6d4c6582013-11-05 22:18:15 +0000975 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000976 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000977 case EM_ConstantFold:
978 return false;
979 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000980 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000981 }
982
983 /// Note that we have had a side-effect, and determine whether we should
984 /// keep evaluating.
985 bool noteSideEffect() {
986 EvalStatus.HasSideEffects = true;
987 return keepEvaluatingAfterSideEffect();
988 }
989
Richard Smithce8eca52015-12-08 03:21:47 +0000990 /// Should we continue evaluation after encountering undefined behavior?
991 bool keepEvaluatingAfterUndefinedBehavior() {
992 switch (EvalMode) {
993 case EM_EvaluateForOverflow:
994 case EM_IgnoreSideEffects:
995 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000996 return true;
997
998 case EM_PotentialConstantExpression:
999 case EM_PotentialConstantExpressionUnevaluated:
1000 case EM_ConstantExpression:
1001 case EM_ConstantExpressionUnevaluated:
1002 return false;
1003 }
1004 llvm_unreachable("Missed EvalMode case");
1005 }
1006
1007 /// Note that we hit something that was technically undefined behavior, but
1008 /// that we can evaluate past it (such as signed overflow or floating-point
1009 /// division by zero.)
1010 bool noteUndefinedBehavior() {
1011 EvalStatus.HasUndefinedBehavior = true;
1012 return keepEvaluatingAfterUndefinedBehavior();
1013 }
1014
Richard Smith253c2a32012-01-27 01:14:48 +00001015 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +00001016 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +00001017 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +00001018 if (!StepsLeft)
1019 return false;
1020
1021 switch (EvalMode) {
1022 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001023 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001024 case EM_EvaluateForOverflow:
1025 return true;
1026
1027 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001028 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001029 case EM_ConstantFold:
1030 case EM_IgnoreSideEffects:
1031 return false;
1032 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001033 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001034 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001035
George Burgess IV8c892b52016-05-25 22:31:54 +00001036 /// Notes that we failed to evaluate an expression that other expressions
1037 /// directly depend on, and determine if we should keep evaluating. This
1038 /// should only be called if we actually intend to keep evaluating.
1039 ///
1040 /// Call noteSideEffect() instead if we may be able to ignore the value that
1041 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1042 ///
1043 /// (Foo(), 1) // use noteSideEffect
1044 /// (Foo() || true) // use noteSideEffect
1045 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001046 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001047 // Failure when evaluating some expression often means there is some
1048 // subexpression whose evaluation was skipped. Therefore, (because we
1049 // don't track whether we skipped an expression when unwinding after an
1050 // evaluation failure) every evaluation failure that bubbles up from a
1051 // subexpression implies that a side-effect has potentially happened. We
1052 // skip setting the HasSideEffects flag to true until we decide to
1053 // continue evaluating after that point, which happens here.
1054 bool KeepGoing = keepEvaluatingAfterFailure();
1055 EvalStatus.HasSideEffects |= KeepGoing;
1056 return KeepGoing;
1057 }
1058
Richard Smith410306b2016-12-12 02:53:20 +00001059 class ArrayInitLoopIndex {
1060 EvalInfo &Info;
1061 uint64_t OuterIndex;
1062
1063 public:
1064 ArrayInitLoopIndex(EvalInfo &Info)
1065 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1066 Info.ArrayInitIndex = 0;
1067 }
1068 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1069
1070 operator uint64_t&() { return Info.ArrayInitIndex; }
1071 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001072 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001073
1074 /// Object used to treat all foldable expressions as constant expressions.
1075 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001076 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001077 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001078 bool HadNoPriorDiags;
1079 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001080
Richard Smith6d4c6582013-11-05 22:18:15 +00001081 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1082 : Info(Info),
1083 Enabled(Enabled),
1084 HadNoPriorDiags(Info.EvalStatus.Diag &&
1085 Info.EvalStatus.Diag->empty() &&
1086 !Info.EvalStatus.HasSideEffects),
1087 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001088 if (Enabled &&
1089 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1090 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001091 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001092 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001093 void keepDiagnostics() { Enabled = false; }
1094 ~FoldConstant() {
1095 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001096 !Info.EvalStatus.HasSideEffects)
1097 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001098 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001099 }
1100 };
Richard Smith17100ba2012-02-16 02:46:34 +00001101
James Y Knight892b09b2018-10-10 02:53:43 +00001102 /// RAII object used to set the current evaluation mode to ignore
1103 /// side-effects.
1104 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001105 EvalInfo &Info;
1106 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001107 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001108 : Info(Info), OldMode(Info.EvalMode) {
1109 if (!Info.checkingPotentialConstantExpression())
James Y Knight892b09b2018-10-10 02:53:43 +00001110 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001111 }
1112
James Y Knight892b09b2018-10-10 02:53:43 +00001113 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001114 };
1115
George Burgess IV8c892b52016-05-25 22:31:54 +00001116 /// RAII object used to optionally suppress diagnostics and side-effects from
1117 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001118 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001119 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001120 Expr::EvalStatus OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001121 unsigned OldSpeculativeEvaluationDepth;
Richard Smith17100ba2012-02-16 02:46:34 +00001122
George Burgess IV8c892b52016-05-25 22:31:54 +00001123 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001124 Info = Other.Info;
1125 OldStatus = Other.OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001126 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001127 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001128 }
1129
1130 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001131 if (!Info)
1132 return;
1133
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001134 Info->EvalStatus = OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001135 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
George Burgess IV8c892b52016-05-25 22:31:54 +00001136 }
1137
Richard Smith17100ba2012-02-16 02:46:34 +00001138 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001139 SpeculativeEvaluationRAII() = default;
1140
1141 SpeculativeEvaluationRAII(
1142 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001143 : Info(&Info), OldStatus(Info.EvalStatus),
Richard Smith37be3362019-05-04 04:00:45 +00001144 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
Richard Smith17100ba2012-02-16 02:46:34 +00001145 Info.EvalStatus.Diag = NewDiag;
Richard Smith37be3362019-05-04 04:00:45 +00001146 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
Richard Smith17100ba2012-02-16 02:46:34 +00001147 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001148
1149 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1150 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1151 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001152 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001153
1154 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1155 maybeRestoreState();
1156 moveFromAndCancel(std::move(Other));
1157 return *this;
1158 }
1159
1160 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001161 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001162
1163 /// RAII object wrapping a full-expression or block scope, and handling
1164 /// the ending of the lifetime of temporaries created within it.
1165 template<bool IsFullExpression>
1166 class ScopeRAII {
1167 EvalInfo &Info;
1168 unsigned OldStackSize;
1169 public:
1170 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001171 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1172 // Push a new temporary version. This is needed to distinguish between
1173 // temporaries created in different iterations of a loop.
1174 Info.CurrentCall->pushTempVersion();
1175 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001176 ~ScopeRAII() {
1177 // Body moved to a static method to encourage the compiler to inline away
1178 // instances of this class.
1179 cleanup(Info, OldStackSize);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001180 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001181 }
1182 private:
1183 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1184 unsigned NewEnd = OldStackSize;
1185 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1186 I != N; ++I) {
1187 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1188 // Full-expression cleanup of a lifetime-extended temporary: nothing
1189 // to do, just move this cleanup to the right place in the stack.
1190 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1191 ++NewEnd;
1192 } else {
1193 // End the lifetime of the object.
1194 Info.CleanupStack[I].endLifetime();
1195 }
1196 }
1197 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1198 Info.CleanupStack.end());
1199 }
1200 };
1201 typedef ScopeRAII<false> BlockScopeRAII;
1202 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001203}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001204
Richard Smitha8105bc2012-01-06 16:39:00 +00001205bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1206 CheckSubobjectKind CSK) {
1207 if (Invalid)
1208 return false;
1209 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001210 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001211 << CSK;
1212 setInvalid();
1213 return false;
1214 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001215 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1216 // must actually be at least one array element; even a VLA cannot have a
1217 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001218 return true;
1219}
1220
Richard Smith6f4f0f12017-10-20 22:56:25 +00001221void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1222 const Expr *E) {
1223 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1224 // Do not set the designator as invalid: we can represent this situation,
1225 // and correct handling of __builtin_object_size requires us to do so.
1226}
1227
Richard Smitha8105bc2012-01-06 16:39:00 +00001228void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001229 const Expr *E,
1230 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001231 // If we're complaining, we must be able to statically determine the size of
1232 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001233 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001234 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001235 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001236 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001237 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001238 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001239 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001240 setInvalid();
1241}
1242
Richard Smithf6f003a2011-12-16 19:06:07 +00001243CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1244 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001245 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001246 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1247 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001248 Info.CurrentCall = this;
1249 ++Info.CallStackDepth;
1250}
1251
1252CallStackFrame::~CallStackFrame() {
1253 assert(Info.CurrentCall == this && "calls retired out of order");
1254 --Info.CallStackDepth;
1255 Info.CurrentCall = Caller;
1256}
1257
Richard Smith08d6a2c2013-07-24 07:11:57 +00001258APValue &CallStackFrame::createTemporary(const void *Key,
1259 bool IsLifetimeExtended) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001260 unsigned Version = Info.CurrentCall->getTempVersion();
1261 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
Richard Smith08d6a2c2013-07-24 07:11:57 +00001262 assert(Result.isUninit() && "temporary created multiple times");
1263 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1264 return Result;
1265}
1266
Richard Smith84401042013-06-03 05:03:02 +00001267static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001268
1269void EvalInfo::addCallStack(unsigned Limit) {
1270 // Determine which calls to skip, if any.
1271 unsigned ActiveCalls = CallStackDepth - 1;
1272 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1273 if (Limit && Limit < ActiveCalls) {
1274 SkipStart = Limit / 2 + Limit % 2;
1275 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001276 }
1277
Richard Smithf6f003a2011-12-16 19:06:07 +00001278 // Walk the call stack and add the diagnostics.
1279 unsigned CallIdx = 0;
1280 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1281 Frame = Frame->Caller, ++CallIdx) {
1282 // Skip this call?
1283 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1284 if (CallIdx == SkipStart) {
1285 // Note that we're skipping calls.
1286 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1287 << unsigned(ActiveCalls - Limit);
1288 }
1289 continue;
1290 }
1291
Richard Smith5179eb72016-06-28 19:03:57 +00001292 // Use a different note for an inheriting constructor, because from the
1293 // user's perspective it's not really a function at all.
1294 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1295 if (CD->isInheritingConstructor()) {
1296 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1297 << CD->getParent();
1298 continue;
1299 }
1300 }
1301
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001302 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001303 llvm::raw_svector_ostream Out(Buffer);
1304 describeCall(Frame, Out);
1305 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1306 }
1307}
1308
Hubert Tong147b7432018-12-12 16:53:43 +00001309/// Kinds of access we can perform on an object, for diagnostics.
1310enum AccessKinds {
1311 AK_Read,
1312 AK_Assign,
1313 AK_Increment,
1314 AK_Decrement
1315};
1316
Richard Smithf6f003a2011-12-16 19:06:07 +00001317namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001318 struct ComplexValue {
1319 private:
1320 bool IsInt;
1321
1322 public:
1323 APSInt IntReal, IntImag;
1324 APFloat FloatReal, FloatImag;
1325
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001326 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001327
1328 void makeComplexFloat() { IsInt = false; }
1329 bool isComplexFloat() const { return !IsInt; }
1330 APFloat &getComplexFloatReal() { return FloatReal; }
1331 APFloat &getComplexFloatImag() { return FloatImag; }
1332
1333 void makeComplexInt() { IsInt = true; }
1334 bool isComplexInt() const { return IsInt; }
1335 APSInt &getComplexIntReal() { return IntReal; }
1336 APSInt &getComplexIntImag() { return IntImag; }
1337
Richard Smith2e312c82012-03-03 22:46:17 +00001338 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001339 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001340 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001341 else
Richard Smith2e312c82012-03-03 22:46:17 +00001342 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001343 }
Richard Smith2e312c82012-03-03 22:46:17 +00001344 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001345 assert(v.isComplexFloat() || v.isComplexInt());
1346 if (v.isComplexFloat()) {
1347 makeComplexFloat();
1348 FloatReal = v.getComplexFloatReal();
1349 FloatImag = v.getComplexFloatImag();
1350 } else {
1351 makeComplexInt();
1352 IntReal = v.getComplexIntReal();
1353 IntImag = v.getComplexIntImag();
1354 }
1355 }
John McCall93d91dc2010-05-07 17:22:02 +00001356 };
John McCall45d55e42010-05-07 21:00:08 +00001357
1358 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001359 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001360 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001361 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001362 bool IsNullPtr : 1;
1363 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001364
Richard Smithce40ad62011-11-12 22:28:03 +00001365 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001366 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001367 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001368 SubobjectDesignator &getLValueDesignator() { return Designator; }
1369 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001370 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001371
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001372 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1373 unsigned getLValueVersion() const { return Base.getVersion(); }
1374
Richard Smith2e312c82012-03-03 22:46:17 +00001375 void moveInto(APValue &V) const {
1376 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001377 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001378 else {
1379 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001380 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001381 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001382 }
John McCall45d55e42010-05-07 21:00:08 +00001383 }
Richard Smith2e312c82012-03-03 22:46:17 +00001384 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001385 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001386 Base = V.getLValueBase();
1387 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001388 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001389 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001390 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001391 }
1392
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001393 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001394#ifndef NDEBUG
1395 // We only allow a few types of invalid bases. Enforce that here.
1396 if (BInvalid) {
1397 const auto *E = B.get<const Expr *>();
1398 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1399 "Unexpected type of invalid base");
1400 }
1401#endif
1402
Richard Smithce40ad62011-11-12 22:28:03 +00001403 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001404 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001405 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001406 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001407 IsNullPtr = false;
1408 }
1409
1410 void setNull(QualType PointerTy, uint64_t TargetVal) {
1411 Base = (Expr *)nullptr;
1412 Offset = CharUnits::fromQuantity(TargetVal);
1413 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001414 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1415 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001416 }
1417
George Burgess IV3a03fab2015-09-04 21:28:13 +00001418 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001419 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001420 }
1421
Hubert Tong147b7432018-12-12 16:53:43 +00001422 private:
Richard Smitha8105bc2012-01-06 16:39:00 +00001423 // Check that this LValue is not based on a null pointer. If it is, produce
1424 // a diagnostic and mark the designator as invalid.
Hubert Tong147b7432018-12-12 16:53:43 +00001425 template <typename GenDiagType>
1426 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001427 if (Designator.Invalid)
1428 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001429 if (IsNullPtr) {
Hubert Tong147b7432018-12-12 16:53:43 +00001430 GenDiag();
Richard Smitha8105bc2012-01-06 16:39:00 +00001431 Designator.setInvalid();
1432 return false;
1433 }
1434 return true;
1435 }
1436
Hubert Tong147b7432018-12-12 16:53:43 +00001437 public:
1438 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1439 CheckSubobjectKind CSK) {
1440 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1441 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1442 });
1443 }
1444
1445 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1446 AccessKinds AK) {
1447 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1448 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1449 });
1450 }
1451
Richard Smitha8105bc2012-01-06 16:39:00 +00001452 // Check this LValue refers to an object. If not, set the designator to be
1453 // invalid and emit a diagnostic.
1454 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001455 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001456 Designator.checkSubobject(Info, E, CSK);
1457 }
1458
1459 void addDecl(EvalInfo &Info, const Expr *E,
1460 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001461 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1462 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001463 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001464 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1465 if (!Designator.Entries.empty()) {
1466 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1467 Designator.setInvalid();
1468 return;
1469 }
Richard Smithefdb5032017-11-15 03:03:56 +00001470 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1471 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1472 Designator.FirstEntryIsAnUnsizedArray = true;
1473 Designator.addUnsizedArrayUnchecked(ElemTy);
1474 }
George Burgess IVe3763372016-12-22 02:50:20 +00001475 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001476 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001477 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1478 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001479 }
Richard Smith66c96992012-02-18 22:04:06 +00001480 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001481 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1482 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001483 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001484 void clearIsNullPointer() {
1485 IsNullPtr = false;
1486 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001487 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1488 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001489 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1490 // but we're not required to diagnose it and it's valid in C++.)
1491 if (!Index)
1492 return;
1493
1494 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1495 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1496 // offsets.
1497 uint64_t Offset64 = Offset.getQuantity();
1498 uint64_t ElemSize64 = ElementSize.getQuantity();
1499 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1500 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1501
1502 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001503 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001504 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001505 }
1506 void adjustOffset(CharUnits N) {
1507 Offset += N;
1508 if (N.getQuantity())
1509 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001510 }
John McCall45d55e42010-05-07 21:00:08 +00001511 };
Richard Smith027bf112011-11-17 22:56:20 +00001512
1513 struct MemberPtr {
1514 MemberPtr() {}
1515 explicit MemberPtr(const ValueDecl *Decl) :
1516 DeclAndIsDerivedMember(Decl, false), Path() {}
1517
1518 /// The member or (direct or indirect) field referred to by this member
1519 /// pointer, or 0 if this is a null member pointer.
1520 const ValueDecl *getDecl() const {
1521 return DeclAndIsDerivedMember.getPointer();
1522 }
1523 /// Is this actually a member of some type derived from the relevant class?
1524 bool isDerivedMember() const {
1525 return DeclAndIsDerivedMember.getInt();
1526 }
1527 /// Get the class which the declaration actually lives in.
1528 const CXXRecordDecl *getContainingRecord() const {
1529 return cast<CXXRecordDecl>(
1530 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1531 }
1532
Richard Smith2e312c82012-03-03 22:46:17 +00001533 void moveInto(APValue &V) const {
1534 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001535 }
Richard Smith2e312c82012-03-03 22:46:17 +00001536 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001537 assert(V.isMemberPointer());
1538 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1539 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1540 Path.clear();
1541 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1542 Path.insert(Path.end(), P.begin(), P.end());
1543 }
1544
1545 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1546 /// whether the member is a member of some class derived from the class type
1547 /// of the member pointer.
1548 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1549 /// Path - The path of base/derived classes from the member declaration's
1550 /// class (exclusive) to the class type of the member pointer (inclusive).
1551 SmallVector<const CXXRecordDecl*, 4> Path;
1552
1553 /// Perform a cast towards the class of the Decl (either up or down the
1554 /// hierarchy).
1555 bool castBack(const CXXRecordDecl *Class) {
1556 assert(!Path.empty());
1557 const CXXRecordDecl *Expected;
1558 if (Path.size() >= 2)
1559 Expected = Path[Path.size() - 2];
1560 else
1561 Expected = getContainingRecord();
1562 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1563 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1564 // if B does not contain the original member and is not a base or
1565 // derived class of the class containing the original member, the result
1566 // of the cast is undefined.
1567 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1568 // (D::*). We consider that to be a language defect.
1569 return false;
1570 }
1571 Path.pop_back();
1572 return true;
1573 }
1574 /// Perform a base-to-derived member pointer cast.
1575 bool castToDerived(const CXXRecordDecl *Derived) {
1576 if (!getDecl())
1577 return true;
1578 if (!isDerivedMember()) {
1579 Path.push_back(Derived);
1580 return true;
1581 }
1582 if (!castBack(Derived))
1583 return false;
1584 if (Path.empty())
1585 DeclAndIsDerivedMember.setInt(false);
1586 return true;
1587 }
1588 /// Perform a derived-to-base member pointer cast.
1589 bool castToBase(const CXXRecordDecl *Base) {
1590 if (!getDecl())
1591 return true;
1592 if (Path.empty())
1593 DeclAndIsDerivedMember.setInt(true);
1594 if (isDerivedMember()) {
1595 Path.push_back(Base);
1596 return true;
1597 }
1598 return castBack(Base);
1599 }
1600 };
Richard Smith357362d2011-12-13 06:39:58 +00001601
Richard Smith7bb00672012-02-01 01:42:44 +00001602 /// Compare two member pointers, which are assumed to be of the same type.
1603 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1604 if (!LHS.getDecl() || !RHS.getDecl())
1605 return !LHS.getDecl() && !RHS.getDecl();
1606 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1607 return false;
1608 return LHS.Path == RHS.Path;
1609 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001610}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001611
Richard Smith2e312c82012-03-03 22:46:17 +00001612static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001613static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1614 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001615 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001616static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1617 bool InvalidBaseOK = false);
1618static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1619 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001620static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1621 EvalInfo &Info);
1622static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001623static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001624static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001625 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001626static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001627static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001628static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1629 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001630static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001631
Leonard Chand3f3e162019-01-18 21:04:25 +00001632/// Evaluate an integer or fixed point expression into an APResult.
1633static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1634 EvalInfo &Info);
1635
1636/// Evaluate only a fixed point expression into an APResult.
1637static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1638 EvalInfo &Info);
1639
Chris Lattner05706e882008-07-11 18:11:29 +00001640//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001641// Misc utilities
1642//===----------------------------------------------------------------------===//
1643
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001644/// A helper function to create a temporary and set an LValue.
1645template <class KeyTy>
1646static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1647 LValue &LV, CallStackFrame &Frame) {
1648 LV.set({Key, Frame.Info.CurrentCall->Index,
1649 Frame.Info.CurrentCall->getTempVersion()});
1650 return Frame.createTemporary(Key, IsLifetimeExtended);
1651}
1652
Richard Smithd6cc1982017-01-31 02:23:02 +00001653/// Negate an APSInt in place, converting it to a signed form if necessary, and
1654/// preserving its value (by extending by up to one bit as needed).
1655static void negateAsSigned(APSInt &Int) {
1656 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1657 Int = Int.extend(Int.getBitWidth() + 1);
1658 Int.setIsSigned(true);
1659 }
1660 Int = -Int;
1661}
1662
Richard Smith84401042013-06-03 05:03:02 +00001663/// Produce a string describing the given constexpr call.
1664static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1665 unsigned ArgIndex = 0;
1666 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1667 !isa<CXXConstructorDecl>(Frame->Callee) &&
1668 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1669
1670 if (!IsMemberCall)
1671 Out << *Frame->Callee << '(';
1672
1673 if (Frame->This && IsMemberCall) {
1674 APValue Val;
1675 Frame->This->moveInto(Val);
1676 Val.printPretty(Out, Frame->Info.Ctx,
1677 Frame->This->Designator.MostDerivedType);
1678 // FIXME: Add parens around Val if needed.
1679 Out << "->" << *Frame->Callee << '(';
1680 IsMemberCall = false;
1681 }
1682
1683 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1684 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1685 if (ArgIndex > (unsigned)IsMemberCall)
1686 Out << ", ";
1687
1688 const ParmVarDecl *Param = *I;
1689 const APValue &Arg = Frame->Arguments[ArgIndex];
1690 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1691
1692 if (ArgIndex == 0 && IsMemberCall)
1693 Out << "->" << *Frame->Callee << '(';
1694 }
1695
1696 Out << ')';
1697}
1698
Richard Smithd9f663b2013-04-22 15:31:51 +00001699/// Evaluate an expression to see if it had side-effects, and discard its
1700/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001701/// \return \c true if the caller should keep evaluating.
1702static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001703 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001704 if (!Evaluate(Scratch, Info, E))
1705 // We don't need the value, but we might have skipped a side effect here.
1706 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001707 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001708}
1709
Richard Smithd62306a2011-11-10 06:34:14 +00001710/// Should this call expression be treated as a string literal?
1711static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001712 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001713 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1714 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1715}
1716
Richard Smithce40ad62011-11-12 22:28:03 +00001717static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001718 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1719 // constant expression of pointer type that evaluates to...
1720
1721 // ... a null pointer value, or a prvalue core constant expression of type
1722 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001723 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001724
Richard Smithce40ad62011-11-12 22:28:03 +00001725 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1726 // ... the address of an object with static storage duration,
1727 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1728 return VD->hasGlobalStorage();
1729 // ... the address of a function,
1730 return isa<FunctionDecl>(D);
1731 }
1732
1733 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001734 switch (E->getStmtClass()) {
1735 default:
1736 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001737 case Expr::CompoundLiteralExprClass: {
1738 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1739 return CLE->isFileScope() && CLE->isLValue();
1740 }
Richard Smithe6c01442013-06-05 00:46:14 +00001741 case Expr::MaterializeTemporaryExprClass:
1742 // A materialized temporary might have been lifetime-extended to static
1743 // storage duration.
1744 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001745 // A string literal has static storage duration.
1746 case Expr::StringLiteralClass:
1747 case Expr::PredefinedExprClass:
1748 case Expr::ObjCStringLiteralClass:
1749 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001750 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001751 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001752 return true;
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001753 case Expr::ObjCBoxedExprClass:
1754 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
Richard Smithd62306a2011-11-10 06:34:14 +00001755 case Expr::CallExprClass:
1756 return IsStringLiteralCall(cast<CallExpr>(E));
1757 // For GCC compatibility, &&label has static storage duration.
1758 case Expr::AddrLabelExprClass:
1759 return true;
1760 // A Block literal expression may be used as the initialization value for
1761 // Block variables at global or local static scope.
1762 case Expr::BlockExprClass:
1763 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001764 case Expr::ImplicitValueInitExprClass:
1765 // FIXME:
1766 // We can never form an lvalue with an implicit value initialization as its
1767 // base through expression evaluation, so these only appear in one case: the
1768 // implicit variable declaration we invent when checking whether a constexpr
1769 // constructor can produce a constant expression. We must assume that such
1770 // an expression might be a global lvalue.
1771 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001772 }
John McCall95007602010-05-10 23:27:23 +00001773}
1774
Richard Smith06f71b52018-08-04 00:57:17 +00001775static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1776 return LVal.Base.dyn_cast<const ValueDecl*>();
1777}
1778
1779static bool IsLiteralLValue(const LValue &Value) {
1780 if (Value.getLValueCallIndex())
1781 return false;
1782 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1783 return E && !isa<MaterializeTemporaryExpr>(E);
1784}
1785
1786static bool IsWeakLValue(const LValue &Value) {
1787 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1788 return Decl && Decl->isWeak();
1789}
1790
1791static bool isZeroSized(const LValue &Value) {
1792 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1793 if (Decl && isa<VarDecl>(Decl)) {
1794 QualType Ty = Decl->getType();
1795 if (Ty->isArrayType())
1796 return Ty->isIncompleteType() ||
1797 Decl->getASTContext().getTypeSize(Ty) == 0;
1798 }
1799 return false;
1800}
1801
1802static bool HasSameBase(const LValue &A, const LValue &B) {
1803 if (!A.getLValueBase())
1804 return !B.getLValueBase();
1805 if (!B.getLValueBase())
1806 return false;
1807
1808 if (A.getLValueBase().getOpaqueValue() !=
1809 B.getLValueBase().getOpaqueValue()) {
1810 const Decl *ADecl = GetLValueBaseDecl(A);
1811 if (!ADecl)
1812 return false;
1813 const Decl *BDecl = GetLValueBaseDecl(B);
1814 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1815 return false;
1816 }
1817
1818 return IsGlobalLValue(A.getLValueBase()) ||
1819 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1820 A.getLValueVersion() == B.getLValueVersion());
1821}
1822
Richard Smithb228a862012-02-15 02:18:13 +00001823static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1824 assert(Base && "no location for a null lvalue");
1825 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1826 if (VD)
1827 Info.Note(VD->getLocation(), diag::note_declared_at);
1828 else
Ted Kremenek28831752012-08-23 20:46:57 +00001829 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001830 diag::note_constexpr_temporary_here);
1831}
1832
Richard Smith80815602011-11-07 05:07:52 +00001833/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001834/// value for an address or reference constant expression. Return true if we
1835/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001836static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001837 QualType Type, const LValue &LVal,
1838 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001839 bool IsReferenceType = Type->isReferenceType();
1840
Richard Smith357362d2011-12-13 06:39:58 +00001841 APValue::LValueBase Base = LVal.getLValueBase();
1842 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1843
Richard Smith0dea49e2012-02-18 04:58:18 +00001844 // Check that the object is a global. Note that the fake 'this' object we
1845 // manufacture when checking potential constant expressions is conservatively
1846 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001847 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001848 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001849 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001850 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001851 << IsReferenceType << !Designator.Entries.empty()
1852 << !!VD << VD;
1853 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001854 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001855 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001856 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001857 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001858 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001859 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001860 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001861 LVal.getLValueCallIndex() == 0) &&
1862 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001863
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001864 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1865 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001866 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001867 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001868 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001869
Hans Wennborg82dd8772014-06-25 22:19:48 +00001870 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001871 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001872 return false;
1873 }
1874 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1875 // __declspec(dllimport) must be handled very carefully:
1876 // We must never initialize an expression with the thunk in C++.
1877 // Doing otherwise would allow the same id-expression to yield
1878 // different addresses for the same function in different translation
1879 // units. However, this means that we must dynamically initialize the
1880 // expression with the contents of the import address table at runtime.
1881 //
1882 // The C language has no notion of ODR; furthermore, it has no notion of
1883 // dynamic initialization. This means that we are permitted to
1884 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001885 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1886 FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001887 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001888 }
1889 }
1890
Richard Smitha8105bc2012-01-06 16:39:00 +00001891 // Allow address constant expressions to be past-the-end pointers. This is
1892 // an extension: the standard requires them to point to an object.
1893 if (!IsReferenceType)
1894 return true;
1895
1896 // A reference constant expression must refer to an object.
1897 if (!Base) {
1898 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001899 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001900 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001901 }
1902
Richard Smith357362d2011-12-13 06:39:58 +00001903 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001904 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001905 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001906 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001907 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001908 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001909 }
1910
Richard Smith80815602011-11-07 05:07:52 +00001911 return true;
1912}
1913
Reid Klecknercd016d82017-07-07 22:04:29 +00001914/// Member pointers are constant expressions unless they point to a
1915/// non-virtual dllimport member function.
1916static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1917 SourceLocation Loc,
1918 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001919 const APValue &Value,
1920 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00001921 const ValueDecl *Member = Value.getMemberPointerDecl();
1922 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1923 if (!FD)
1924 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001925 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1926 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00001927}
1928
Richard Smithfddd3842011-12-30 21:15:51 +00001929/// Check that this core constant expression is of literal type, and if not,
1930/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001931static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001932 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001933 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001934 return true;
1935
Richard Smith7525ff62013-05-09 07:14:00 +00001936 // C++1y: A constant initializer for an object o [...] may also invoke
1937 // constexpr constructors for o and its subobjects even if those objects
1938 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001939 //
1940 // C++11 missed this detail for aggregates, so classes like this:
1941 // struct foo_t { union { int i; volatile int j; } u; };
1942 // are not (obviously) initializable like so:
1943 // __attribute__((__require_constant_initialization__))
1944 // static const foo_t x = {{0}};
1945 // because "i" is a subobject with non-literal initialization (due to the
1946 // volatile member of the union). See:
1947 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1948 // Therefore, we use the C++1y behavior.
1949 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001950 return true;
1951
Richard Smithfddd3842011-12-30 21:15:51 +00001952 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001953 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001954 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001955 << E->getType();
1956 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001957 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001958 return false;
1959}
1960
Richard Smith0b0a0b62011-10-29 20:57:55 +00001961/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001962/// constant expression. If not, report an appropriate diagnostic. Does not
1963/// check that the expression is of literal type.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001964static bool
1965CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1966 const APValue &Value,
1967 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
Richard Smith1a90f592013-06-18 17:51:51 +00001968 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001969 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001970 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001971 return false;
1972 }
1973
Richard Smith77be48a2014-07-31 06:31:19 +00001974 // We allow _Atomic(T) to be initialized from anything that T can be
1975 // initialized from.
1976 if (const AtomicType *AT = Type->getAs<AtomicType>())
1977 Type = AT->getValueType();
1978
Richard Smithb228a862012-02-15 02:18:13 +00001979 // Core issue 1454: For a literal constant expression of array or class type,
1980 // each subobject of its value shall have been initialized by a constant
1981 // expression.
1982 if (Value.isArray()) {
1983 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1984 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1985 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001986 Value.getArrayInitializedElt(I), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001987 return false;
1988 }
1989 if (!Value.hasArrayFiller())
1990 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001991 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
1992 Usage);
Richard Smith80815602011-11-07 05:07:52 +00001993 }
Richard Smithb228a862012-02-15 02:18:13 +00001994 if (Value.isUnion() && Value.getUnionField()) {
1995 return CheckConstantExpression(Info, DiagLoc,
1996 Value.getUnionField()->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00001997 Value.getUnionValue(), Usage);
Richard Smithb228a862012-02-15 02:18:13 +00001998 }
1999 if (Value.isStruct()) {
2000 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2001 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2002 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002003 for (const CXXBaseSpecifier &BS : CD->bases()) {
2004 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
2005 Value.getStructBase(BaseIndex), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00002006 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002007 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00002008 }
2009 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002010 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00002011 if (I->isUnnamedBitfield())
2012 continue;
2013
David Blaikie2d7c57e2012-04-30 02:36:29 +00002014 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00002015 Value.getStructField(I->getFieldIndex()),
2016 Usage))
Richard Smithb228a862012-02-15 02:18:13 +00002017 return false;
2018 }
2019 }
2020
2021 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00002022 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00002023 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00002024 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00002025 }
2026
Reid Klecknercd016d82017-07-07 22:04:29 +00002027 if (Value.isMemberPointer())
Reid Kleckner1a840d22018-05-10 18:57:35 +00002028 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00002029
Richard Smithb228a862012-02-15 02:18:13 +00002030 // Everything else is fine.
2031 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002032}
2033
Richard Smith2e312c82012-03-03 22:46:17 +00002034static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00002035 // A null base expression indicates a null pointer. These are always
2036 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00002037 if (!Value.getLValueBase()) {
2038 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00002039 return true;
2040 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00002041
Richard Smith027bf112011-11-17 22:56:20 +00002042 // We have a non-null base. These are generally known to be true, but if it's
2043 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00002044 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00002045 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00002046 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00002047}
2048
Richard Smith2e312c82012-03-03 22:46:17 +00002049static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00002050 switch (Val.getKind()) {
2051 case APValue::Uninitialized:
2052 return false;
2053 case APValue::Int:
2054 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002055 return true;
Leonard Chan86285d22019-01-16 18:53:05 +00002056 case APValue::FixedPoint:
2057 Result = Val.getFixedPoint().getBoolValue();
2058 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002059 case APValue::Float:
2060 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002061 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002062 case APValue::ComplexInt:
2063 Result = Val.getComplexIntReal().getBoolValue() ||
2064 Val.getComplexIntImag().getBoolValue();
2065 return true;
2066 case APValue::ComplexFloat:
2067 Result = !Val.getComplexFloatReal().isZero() ||
2068 !Val.getComplexFloatImag().isZero();
2069 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002070 case APValue::LValue:
2071 return EvalPointerValueAsBool(Val, Result);
2072 case APValue::MemberPointer:
2073 Result = Val.getMemberPointerDecl();
2074 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002075 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002076 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002077 case APValue::Struct:
2078 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002079 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002080 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002081 }
2082
Richard Smith11562c52011-10-28 17:51:58 +00002083 llvm_unreachable("unknown APValue kind");
2084}
2085
2086static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2087 EvalInfo &Info) {
2088 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002089 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002090 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002091 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002092 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002093}
2094
Richard Smith357362d2011-12-13 06:39:58 +00002095template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002096static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002097 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002098 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002099 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002100 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002101}
2102
2103static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2104 QualType SrcType, const APFloat &Value,
2105 QualType DestType, APSInt &Result) {
2106 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002107 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002108 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002109
Richard Smith357362d2011-12-13 06:39:58 +00002110 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002111 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002112 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2113 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002114 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002115 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002116}
2117
Richard Smith357362d2011-12-13 06:39:58 +00002118static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2119 QualType SrcType, QualType DestType,
2120 APFloat &Result) {
2121 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002122 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002123 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2124 APFloat::rmNearestTiesToEven, &ignored)
2125 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002126 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002127 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002128}
2129
Richard Smith911e1422012-01-30 22:27:01 +00002130static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2131 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002132 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002133 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002134 // Figure out if this is a truncate, extend or noop cast.
2135 // If the input is signed, do a sign extend, noop, or truncate.
Richard Smithbd844e02018-11-12 20:11:57 +00002136 APSInt Result = Value.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002137 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Richard Smithbd844e02018-11-12 20:11:57 +00002138 if (DestType->isBooleanType())
2139 Result = Value.getBoolValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002140 return Result;
2141}
2142
Richard Smith357362d2011-12-13 06:39:58 +00002143static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2144 QualType SrcType, const APSInt &Value,
2145 QualType DestType, APFloat &Result) {
2146 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2147 if (Result.convertFromAPInt(Value, Value.isSigned(),
2148 APFloat::rmNearestTiesToEven)
2149 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002150 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002151 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002152}
2153
Richard Smith49ca8aa2013-08-06 07:09:20 +00002154static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2155 APValue &Value, const FieldDecl *FD) {
2156 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2157
2158 if (!Value.isInt()) {
2159 // Trying to store a pointer-cast-to-integer into a bitfield.
2160 // FIXME: In this case, we should provide the diagnostic for casting
2161 // a pointer to an integer.
2162 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002163 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002164 return false;
2165 }
2166
2167 APSInt &Int = Value.getInt();
2168 unsigned OldBitWidth = Int.getBitWidth();
2169 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2170 if (NewBitWidth < OldBitWidth)
2171 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2172 return true;
2173}
2174
Eli Friedman803acb32011-12-22 03:51:45 +00002175static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2176 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002177 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002178 if (!Evaluate(SVal, Info, E))
2179 return false;
2180 if (SVal.isInt()) {
2181 Res = SVal.getInt();
2182 return true;
2183 }
2184 if (SVal.isFloat()) {
2185 Res = SVal.getFloat().bitcastToAPInt();
2186 return true;
2187 }
2188 if (SVal.isVector()) {
2189 QualType VecTy = E->getType();
2190 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2191 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2192 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2193 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2194 Res = llvm::APInt::getNullValue(VecSize);
2195 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2196 APValue &Elt = SVal.getVectorElt(i);
2197 llvm::APInt EltAsInt;
2198 if (Elt.isInt()) {
2199 EltAsInt = Elt.getInt();
2200 } else if (Elt.isFloat()) {
2201 EltAsInt = Elt.getFloat().bitcastToAPInt();
2202 } else {
2203 // Don't try to handle vectors of anything other than int or float
2204 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002205 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002206 return false;
2207 }
2208 unsigned BaseEltSize = EltAsInt.getBitWidth();
2209 if (BigEndian)
2210 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2211 else
2212 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2213 }
2214 return true;
2215 }
2216 // Give up if the input isn't an int, float, or vector. For example, we
2217 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002218 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002219 return false;
2220}
2221
Richard Smith43e77732013-05-07 04:50:00 +00002222/// Perform the given integer operation, which is known to need at most BitWidth
2223/// bits, and check for overflow in the original type (if that type was not an
2224/// unsigned type).
2225template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002226static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2227 const APSInt &LHS, const APSInt &RHS,
2228 unsigned BitWidth, Operation Op,
2229 APSInt &Result) {
2230 if (LHS.isUnsigned()) {
2231 Result = Op(LHS, RHS);
2232 return true;
2233 }
Richard Smith43e77732013-05-07 04:50:00 +00002234
2235 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002236 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002237 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002238 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002239 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002240 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002241 << Result.toString(10) << E->getType();
2242 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002243 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002244 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002245 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002246}
2247
2248/// Perform the given binary integer operation.
2249static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2250 BinaryOperatorKind Opcode, APSInt RHS,
2251 APSInt &Result) {
2252 switch (Opcode) {
2253 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002254 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002255 return false;
2256 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002257 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2258 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002259 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002260 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2261 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002262 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002263 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2264 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002265 case BO_And: Result = LHS & RHS; return true;
2266 case BO_Xor: Result = LHS ^ RHS; return true;
2267 case BO_Or: Result = LHS | RHS; return true;
2268 case BO_Div:
2269 case BO_Rem:
2270 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002271 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002272 return false;
2273 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002274 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2275 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2276 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002277 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2278 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002279 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2280 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002281 return true;
2282 case BO_Shl: {
2283 if (Info.getLangOpts().OpenCL)
2284 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2285 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2286 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2287 RHS.isUnsigned());
2288 else if (RHS.isSigned() && RHS.isNegative()) {
2289 // During constant-folding, a negative shift is an opposite shift. Such
2290 // a shift is not a constant expression.
2291 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2292 RHS = -RHS;
2293 goto shift_right;
2294 }
2295 shift_left:
2296 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2297 // the shifted type.
2298 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2299 if (SA != RHS) {
2300 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2301 << RHS << E->getType() << LHS.getBitWidth();
2302 } else if (LHS.isSigned()) {
2303 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2304 // operand, and must not overflow the corresponding unsigned type.
2305 if (LHS.isNegative())
2306 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2307 else if (LHS.countLeadingZeros() < SA)
2308 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2309 }
2310 Result = LHS << SA;
2311 return true;
2312 }
2313 case BO_Shr: {
2314 if (Info.getLangOpts().OpenCL)
2315 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2316 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2317 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2318 RHS.isUnsigned());
2319 else if (RHS.isSigned() && RHS.isNegative()) {
2320 // During constant-folding, a negative shift is an opposite shift. Such a
2321 // shift is not a constant expression.
2322 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2323 RHS = -RHS;
2324 goto shift_left;
2325 }
2326 shift_right:
2327 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2328 // shifted type.
2329 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2330 if (SA != RHS)
2331 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2332 << RHS << E->getType() << LHS.getBitWidth();
2333 Result = LHS >> SA;
2334 return true;
2335 }
2336
2337 case BO_LT: Result = LHS < RHS; return true;
2338 case BO_GT: Result = LHS > RHS; return true;
2339 case BO_LE: Result = LHS <= RHS; return true;
2340 case BO_GE: Result = LHS >= RHS; return true;
2341 case BO_EQ: Result = LHS == RHS; return true;
2342 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002343 case BO_Cmp:
2344 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002345 }
2346}
2347
Richard Smith861b5b52013-05-07 23:34:45 +00002348/// Perform the given binary floating-point operation, in-place, on LHS.
2349static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2350 APFloat &LHS, BinaryOperatorKind Opcode,
2351 const APFloat &RHS) {
2352 switch (Opcode) {
2353 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002354 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002355 return false;
2356 case BO_Mul:
2357 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2358 break;
2359 case BO_Add:
2360 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2361 break;
2362 case BO_Sub:
2363 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2364 break;
2365 case BO_Div:
2366 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2367 break;
2368 }
2369
Richard Smith0c6124b2015-12-03 01:36:22 +00002370 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002371 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002372 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002373 }
Richard Smith861b5b52013-05-07 23:34:45 +00002374 return true;
2375}
2376
Richard Smitha8105bc2012-01-06 16:39:00 +00002377/// Cast an lvalue referring to a base subobject to a derived class, by
2378/// truncating the lvalue's path to the given length.
2379static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2380 const RecordDecl *TruncatedType,
2381 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002382 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002383
2384 // Check we actually point to a derived class object.
2385 if (TruncatedElements == D.Entries.size())
2386 return true;
2387 assert(TruncatedElements >= D.MostDerivedPathLength &&
2388 "not casting to a derived class");
2389 if (!Result.checkSubobject(Info, E, CSK_Derived))
2390 return false;
2391
2392 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002393 const RecordDecl *RD = TruncatedType;
2394 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002395 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002396 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2397 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002398 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002399 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002400 else
Richard Smithd62306a2011-11-10 06:34:14 +00002401 Result.Offset -= Layout.getBaseClassOffset(Base);
2402 RD = Base;
2403 }
Richard Smith027bf112011-11-17 22:56:20 +00002404 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002405 return true;
2406}
2407
John McCalld7bca762012-05-01 00:38:49 +00002408static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002409 const CXXRecordDecl *Derived,
2410 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002411 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002412 if (!RL) {
2413 if (Derived->isInvalidDecl()) return false;
2414 RL = &Info.Ctx.getASTRecordLayout(Derived);
2415 }
2416
Richard Smithd62306a2011-11-10 06:34:14 +00002417 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002418 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002419 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002420}
2421
Richard Smitha8105bc2012-01-06 16:39:00 +00002422static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002423 const CXXRecordDecl *DerivedDecl,
2424 const CXXBaseSpecifier *Base) {
2425 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2426
John McCalld7bca762012-05-01 00:38:49 +00002427 if (!Base->isVirtual())
2428 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002429
Richard Smitha8105bc2012-01-06 16:39:00 +00002430 SubobjectDesignator &D = Obj.Designator;
2431 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002432 return false;
2433
Richard Smitha8105bc2012-01-06 16:39:00 +00002434 // Extract most-derived object and corresponding type.
2435 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2436 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2437 return false;
2438
2439 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002440 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002441 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2442 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002443 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002444 return true;
2445}
2446
Richard Smith84401042013-06-03 05:03:02 +00002447static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2448 QualType Type, LValue &Result) {
2449 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2450 PathE = E->path_end();
2451 PathI != PathE; ++PathI) {
2452 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2453 *PathI))
2454 return false;
2455 Type = (*PathI)->getType();
2456 }
2457 return true;
2458}
2459
Richard Smithd62306a2011-11-10 06:34:14 +00002460/// Update LVal to refer to the given field, which must be a member of the type
2461/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002462static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002463 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002464 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002465 if (!RL) {
2466 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002467 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002468 }
Richard Smithd62306a2011-11-10 06:34:14 +00002469
2470 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002471 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002472 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002473 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002474}
2475
Richard Smith1b78b3d2012-01-25 22:15:11 +00002476/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002477static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002478 LValue &LVal,
2479 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002480 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002481 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002482 return false;
2483 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002484}
2485
Richard Smithd62306a2011-11-10 06:34:14 +00002486/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002487static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2488 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002489 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2490 // extension.
2491 if (Type->isVoidType() || Type->isFunctionType()) {
2492 Size = CharUnits::One();
2493 return true;
2494 }
2495
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002496 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002497 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002498 return false;
2499 }
2500
Richard Smithd62306a2011-11-10 06:34:14 +00002501 if (!Type->isConstantSizeType()) {
2502 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002503 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002504 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002505 return false;
2506 }
2507
2508 Size = Info.Ctx.getTypeSizeInChars(Type);
2509 return true;
2510}
2511
2512/// Update a pointer value to model pointer arithmetic.
2513/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002514/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002515/// \param LVal - The pointer value to be updated.
2516/// \param EltTy - The pointee type represented by LVal.
2517/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002518static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2519 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002520 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002521 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002522 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002523 return false;
2524
Yaxun Liu402804b2016-12-15 08:09:08 +00002525 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002526 return true;
2527}
2528
Richard Smithd6cc1982017-01-31 02:23:02 +00002529static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2530 LValue &LVal, QualType EltTy,
2531 int64_t Adjustment) {
2532 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2533 APSInt::get(Adjustment));
2534}
2535
Richard Smith66c96992012-02-18 22:04:06 +00002536/// Update an lvalue to refer to a component of a complex number.
2537/// \param Info - Information about the ongoing evaluation.
2538/// \param LVal - The lvalue to be updated.
2539/// \param EltTy - The complex number's component type.
2540/// \param Imag - False for the real component, true for the imaginary.
2541static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2542 LValue &LVal, QualType EltTy,
2543 bool Imag) {
2544 if (Imag) {
2545 CharUnits SizeOfComponent;
2546 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2547 return false;
2548 LVal.Offset += SizeOfComponent;
2549 }
2550 LVal.addComplex(Info, E, EltTy, Imag);
2551 return true;
2552}
2553
Faisal Vali051e3a22017-02-16 04:12:21 +00002554static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2555 QualType Type, const LValue &LVal,
2556 APValue &RVal);
2557
Richard Smith27908702011-10-24 17:54:18 +00002558/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002559///
2560/// \param Info Information about the ongoing evaluation.
2561/// \param E An expression to be used when printing diagnostics.
2562/// \param VD The variable whose initializer should be obtained.
2563/// \param Frame The frame in which the variable was created. Must be null
2564/// if this variable is not local to the evaluation.
2565/// \param Result Filled in with a pointer to the value of the variable.
2566static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2567 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002568 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002569
Richard Smith254a73d2011-10-28 22:34:42 +00002570 // If this is a parameter to an active constexpr function call, perform
2571 // argument substitution.
2572 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002573 // Assume arguments of a potential constant expression are unknown
2574 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002575 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002576 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002577 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002578 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002579 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002580 }
Richard Smith3229b742013-05-05 21:17:10 +00002581 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002582 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002583 }
Richard Smith27908702011-10-24 17:54:18 +00002584
Richard Smithd9f663b2013-04-22 15:31:51 +00002585 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002586 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002587 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2588 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002589 if (!Result) {
2590 // Assume variables referenced within a lambda's call operator that were
2591 // not declared within the call operator are captures and during checking
2592 // of a potential constant expression, assume they are unknown constant
2593 // expressions.
2594 assert(isLambdaCallOperator(Frame->Callee) &&
2595 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2596 "missing value for local variable");
2597 if (Info.checkingPotentialConstantExpression())
2598 return false;
2599 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002600 Info.FFDiag(E->getBeginLoc(),
2601 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002602 << "captures not currently allowed";
2603 return false;
2604 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002605 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002606 }
2607
Richard Smithd0b4dd62011-12-19 06:19:21 +00002608 // Dig out the initializer, and use the declaration which it's attached to.
2609 const Expr *Init = VD->getAnyInitializer(VD);
2610 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002611 // If we're checking a potential constant expression, the variable could be
2612 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002613 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002614 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002615 return false;
2616 }
2617
Richard Smithd62306a2011-11-10 06:34:14 +00002618 // If we're currently evaluating the initializer of this declaration, use that
2619 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002620 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002621 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002622 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002623 }
2624
Richard Smithcecf1842011-11-01 21:06:14 +00002625 // Never evaluate the initializer of a weak variable. We can't be sure that
2626 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002627 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002628 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002629 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002630 }
Richard Smithcecf1842011-11-01 21:06:14 +00002631
Richard Smithd0b4dd62011-12-19 06:19:21 +00002632 // Check that we can fold the initializer. In C++, we will have already done
2633 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002634 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002635 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002636 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002637 Notes.size() + 1) << VD;
2638 Info.Note(VD->getLocation(), diag::note_declared_at);
2639 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002640 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002641 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002642 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002643 Notes.size() + 1) << VD;
2644 Info.Note(VD->getLocation(), diag::note_declared_at);
2645 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002646 }
Richard Smith27908702011-10-24 17:54:18 +00002647
Richard Smith3229b742013-05-05 21:17:10 +00002648 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002649 return true;
Richard Smith27908702011-10-24 17:54:18 +00002650}
2651
Richard Smith11562c52011-10-28 17:51:58 +00002652static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002653 Qualifiers Quals = T.getQualifiers();
2654 return Quals.hasConst() && !Quals.hasVolatile();
2655}
2656
Richard Smithe97cbd72011-11-11 04:05:33 +00002657/// Get the base index of the given base class within an APValue representing
2658/// the given derived class.
2659static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2660 const CXXRecordDecl *Base) {
2661 Base = Base->getCanonicalDecl();
2662 unsigned Index = 0;
2663 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2664 E = Derived->bases_end(); I != E; ++I, ++Index) {
2665 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2666 return Index;
2667 }
2668
2669 llvm_unreachable("base class missing from derived class's bases list");
2670}
2671
Richard Smith3da88fa2013-04-26 14:36:30 +00002672/// Extract the value of a character from a string literal.
2673static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2674 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002675 // FIXME: Support MakeStringConstant
2676 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2677 std::string Str;
2678 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2679 assert(Index <= Str.size() && "Index too large");
2680 return APSInt::getUnsigned(Str.c_str()[Index]);
2681 }
2682
Alexey Bataevec474782014-10-09 08:45:04 +00002683 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2684 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002685 const StringLiteral *S = cast<StringLiteral>(Lit);
2686 const ConstantArrayType *CAT =
2687 Info.Ctx.getAsConstantArrayType(S->getType());
2688 assert(CAT && "string literal isn't an array");
2689 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002690 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002691
2692 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002693 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002694 if (Index < S->getLength())
2695 Value = S->getCodeUnit(Index);
2696 return Value;
2697}
2698
Richard Smith3da88fa2013-04-26 14:36:30 +00002699// Expand a string literal into an array of characters.
Eli Friedman3bf72d72019-02-08 21:18:46 +00002700//
2701// FIXME: This is inefficient; we should probably introduce something similar
2702// to the LLVM ConstantDataArray to make this cheaper.
2703static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
Richard Smith3da88fa2013-04-26 14:36:30 +00002704 APValue &Result) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002705 const ConstantArrayType *CAT =
2706 Info.Ctx.getAsConstantArrayType(S->getType());
2707 assert(CAT && "string literal isn't an array");
2708 QualType CharType = CAT->getElementType();
2709 assert(CharType->isIntegerType() && "unexpected character type");
2710
2711 unsigned Elts = CAT->getSize().getZExtValue();
2712 Result = APValue(APValue::UninitArray(),
2713 std::min(S->getLength(), Elts), Elts);
2714 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2715 CharType->isUnsignedIntegerType());
2716 if (Result.hasArrayFiller())
2717 Result.getArrayFiller() = APValue(Value);
2718 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2719 Value = S->getCodeUnit(I);
2720 Result.getArrayInitializedElt(I) = APValue(Value);
2721 }
2722}
2723
2724// Expand an array so that it has more than Index filled elements.
2725static void expandArray(APValue &Array, unsigned Index) {
2726 unsigned Size = Array.getArraySize();
2727 assert(Index < Size);
2728
2729 // Always at least double the number of elements for which we store a value.
2730 unsigned OldElts = Array.getArrayInitializedElts();
2731 unsigned NewElts = std::max(Index+1, OldElts * 2);
2732 NewElts = std::min(Size, std::max(NewElts, 8u));
2733
2734 // Copy the data across.
2735 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2736 for (unsigned I = 0; I != OldElts; ++I)
2737 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2738 for (unsigned I = OldElts; I != NewElts; ++I)
2739 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2740 if (NewValue.hasArrayFiller())
2741 NewValue.getArrayFiller() = Array.getArrayFiller();
2742 Array.swap(NewValue);
2743}
2744
Richard Smithb01fe402014-09-16 01:24:02 +00002745/// Determine whether a type would actually be read by an lvalue-to-rvalue
2746/// conversion. If it's of class type, we may assume that the copy operation
2747/// is trivial. Note that this is never true for a union type with fields
2748/// (because the copy always "reads" the active member) and always true for
2749/// a non-class type.
2750static bool isReadByLvalueToRvalueConversion(QualType T) {
2751 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2752 if (!RD || (RD->isUnion() && !RD->field_empty()))
2753 return true;
2754 if (RD->isEmpty())
2755 return false;
2756
2757 for (auto *Field : RD->fields())
2758 if (isReadByLvalueToRvalueConversion(Field->getType()))
2759 return true;
2760
2761 for (auto &BaseSpec : RD->bases())
2762 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2763 return true;
2764
2765 return false;
2766}
2767
2768/// Diagnose an attempt to read from any unreadable field within the specified
2769/// type, which might be a class type.
2770static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2771 QualType T) {
2772 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2773 if (!RD)
2774 return false;
2775
2776 if (!RD->hasMutableFields())
2777 return false;
2778
2779 for (auto *Field : RD->fields()) {
2780 // If we're actually going to read this field in some way, then it can't
2781 // be mutable. If we're in a union, then assigning to a mutable field
2782 // (even an empty one) can change the active member, so that's not OK.
2783 // FIXME: Add core issue number for the union case.
2784 if (Field->isMutable() &&
2785 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002786 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002787 Info.Note(Field->getLocation(), diag::note_declared_at);
2788 return true;
2789 }
2790
2791 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2792 return true;
2793 }
2794
2795 for (auto &BaseSpec : RD->bases())
2796 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2797 return true;
2798
2799 // All mutable fields were empty, and thus not actually read.
2800 return false;
2801}
2802
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002803namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002804/// A handle to a complete object (an object that is not a subobject of
2805/// another object).
2806struct CompleteObject {
2807 /// The value of the complete object.
2808 APValue *Value;
2809 /// The type of the complete object.
2810 QualType Type;
Richard Smith9defb7d2018-02-21 03:38:30 +00002811 bool LifetimeStartedInEvaluation;
Richard Smith3229b742013-05-05 21:17:10 +00002812
Craig Topper36250ad2014-05-12 05:36:57 +00002813 CompleteObject() : Value(nullptr) {}
Richard Smith9defb7d2018-02-21 03:38:30 +00002814 CompleteObject(APValue *Value, QualType Type,
2815 bool LifetimeStartedInEvaluation)
2816 : Value(Value), Type(Type),
2817 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
Richard Smith3229b742013-05-05 21:17:10 +00002818 assert(Value && "missing value for complete object");
2819 }
2820
Aaron Ballman67347662015-02-15 22:00:28 +00002821 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002822};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002823} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002824
Richard Smith3da88fa2013-04-26 14:36:30 +00002825/// Find the designated sub-object of an rvalue.
2826template<typename SubobjectHandler>
2827typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002828findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002829 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002830 if (Sub.Invalid)
2831 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002832 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002833 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002834 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002835 Info.FFDiag(E, Sub.isOnePastTheEnd()
2836 ? diag::note_constexpr_access_past_end
2837 : diag::note_constexpr_access_unsized_array)
2838 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002839 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002840 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002841 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002842 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002843
Richard Smith3229b742013-05-05 21:17:10 +00002844 APValue *O = Obj.Value;
2845 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002846 const FieldDecl *LastField = nullptr;
Richard Smith9defb7d2018-02-21 03:38:30 +00002847 const bool MayReadMutableMembers =
2848 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002849
Richard Smithd62306a2011-11-10 06:34:14 +00002850 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002851 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2852 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002853 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002854 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002855 return handler.failed();
2856 }
2857
Richard Smith49ca8aa2013-08-06 07:09:20 +00002858 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002859 // If we are reading an object of class type, there may still be more
2860 // things we need to check: if there are any mutable subobjects, we
2861 // cannot perform this read. (This only happens when performing a trivial
2862 // copy or assignment.)
2863 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smith9defb7d2018-02-21 03:38:30 +00002864 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002865 return handler.failed();
2866
Richard Smith49ca8aa2013-08-06 07:09:20 +00002867 if (!handler.found(*O, ObjType))
2868 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002869
Richard Smith49ca8aa2013-08-06 07:09:20 +00002870 // If we modified a bit-field, truncate it to the right width.
2871 if (handler.AccessKind != AK_Read &&
2872 LastField && LastField->isBitField() &&
2873 !truncateBitfieldValue(Info, E, *O, LastField))
2874 return false;
2875
2876 return true;
2877 }
2878
Craig Topper36250ad2014-05-12 05:36:57 +00002879 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002880 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002881 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002882 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002883 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002884 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002885 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002886 // Note, it should not be possible to form a pointer with a valid
2887 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002888 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002889 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002890 << handler.AccessKind;
2891 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002892 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002893 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002894 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002895
2896 ObjType = CAT->getElementType();
2897
Richard Smith3da88fa2013-04-26 14:36:30 +00002898 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002899 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002900 else if (handler.AccessKind != AK_Read) {
2901 expandArray(*O, Index);
2902 O = &O->getArrayInitializedElt(Index);
2903 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002904 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002905 } else if (ObjType->isAnyComplexType()) {
2906 // Next subobject is a complex number.
2907 uint64_t Index = Sub.Entries[I].ArrayIndex;
2908 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002909 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002910 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002911 << handler.AccessKind;
2912 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002913 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002914 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002915 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002916
2917 bool WasConstQualified = ObjType.isConstQualified();
2918 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2919 if (WasConstQualified)
2920 ObjType.addConst();
2921
Richard Smith66c96992012-02-18 22:04:06 +00002922 assert(I == N - 1 && "extracting subobject of scalar?");
2923 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002924 return handler.found(Index ? O->getComplexIntImag()
2925 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002926 } else {
2927 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002928 return handler.found(Index ? O->getComplexFloatImag()
2929 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002930 }
Richard Smithd62306a2011-11-10 06:34:14 +00002931 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00002932 // In C++14 onwards, it is permitted to read a mutable member whose
2933 // lifetime began within the evaluation.
2934 // FIXME: Should we also allow this in C++11?
2935 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2936 !MayReadMutableMembers) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002937 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002938 << Field;
2939 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002940 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002941 }
2942
Richard Smithd62306a2011-11-10 06:34:14 +00002943 // Next subobject is a class, struct or union field.
2944 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2945 if (RD->isUnion()) {
2946 const FieldDecl *UnionField = O->getUnionField();
2947 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002948 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002949 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002950 << handler.AccessKind << Field << !UnionField << UnionField;
2951 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002952 }
Richard Smithd62306a2011-11-10 06:34:14 +00002953 O = &O->getUnionValue();
2954 } else
2955 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002956
2957 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002958 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002959 if (WasConstQualified && !Field->isMutable())
2960 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002961
2962 if (ObjType.isVolatileQualified()) {
2963 if (Info.getLangOpts().CPlusPlus) {
2964 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002965 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002966 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002967 Info.Note(Field->getLocation(), diag::note_declared_at);
2968 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002969 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002970 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002971 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002972 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002973
2974 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002975 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002976 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002977 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2978 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2979 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002980
2981 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002982 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002983 if (WasConstQualified)
2984 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002985 }
2986 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002987}
2988
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002989namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002990struct ExtractSubobjectHandler {
2991 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002992 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002993
2994 static const AccessKinds AccessKind = AK_Read;
2995
2996 typedef bool result_type;
2997 bool failed() { return false; }
2998 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002999 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00003000 return true;
3001 }
3002 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003003 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003004 return true;
3005 }
3006 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003007 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003008 return true;
3009 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003010};
Richard Smith3229b742013-05-05 21:17:10 +00003011} // end anonymous namespace
3012
Richard Smith3da88fa2013-04-26 14:36:30 +00003013const AccessKinds ExtractSubobjectHandler::AccessKind;
3014
3015/// Extract the designated sub-object of an rvalue.
3016static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003017 const CompleteObject &Obj,
3018 const SubobjectDesignator &Sub,
3019 APValue &Result) {
3020 ExtractSubobjectHandler Handler = { Info, Result };
3021 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00003022}
3023
Richard Smith3229b742013-05-05 21:17:10 +00003024namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003025struct ModifySubobjectHandler {
3026 EvalInfo &Info;
3027 APValue &NewVal;
3028 const Expr *E;
3029
3030 typedef bool result_type;
3031 static const AccessKinds AccessKind = AK_Assign;
3032
3033 bool checkConst(QualType QT) {
3034 // Assigning to a const object has undefined behavior.
3035 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003036 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003037 return false;
3038 }
3039 return true;
3040 }
3041
3042 bool failed() { return false; }
3043 bool found(APValue &Subobj, QualType SubobjType) {
3044 if (!checkConst(SubobjType))
3045 return false;
3046 // We've been given ownership of NewVal, so just swap it in.
3047 Subobj.swap(NewVal);
3048 return true;
3049 }
3050 bool found(APSInt &Value, QualType SubobjType) {
3051 if (!checkConst(SubobjType))
3052 return false;
3053 if (!NewVal.isInt()) {
3054 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003055 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003056 return false;
3057 }
3058 Value = NewVal.getInt();
3059 return true;
3060 }
3061 bool found(APFloat &Value, QualType SubobjType) {
3062 if (!checkConst(SubobjType))
3063 return false;
3064 Value = NewVal.getFloat();
3065 return true;
3066 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003067};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003068} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003069
Richard Smith3229b742013-05-05 21:17:10 +00003070const AccessKinds ModifySubobjectHandler::AccessKind;
3071
Richard Smith3da88fa2013-04-26 14:36:30 +00003072/// Update the designated sub-object of an rvalue to the given value.
3073static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003074 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003075 const SubobjectDesignator &Sub,
3076 APValue &NewVal) {
3077 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003078 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003079}
3080
Richard Smith84f6dcf2012-02-02 01:16:57 +00003081/// Find the position where two subobject designators diverge, or equivalently
3082/// the length of the common initial subsequence.
3083static unsigned FindDesignatorMismatch(QualType ObjType,
3084 const SubobjectDesignator &A,
3085 const SubobjectDesignator &B,
3086 bool &WasArrayIndex) {
3087 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3088 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003089 if (!ObjType.isNull() &&
3090 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003091 // Next subobject is an array element.
3092 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3093 WasArrayIndex = true;
3094 return I;
3095 }
Richard Smith66c96992012-02-18 22:04:06 +00003096 if (ObjType->isAnyComplexType())
3097 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3098 else
3099 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003100 } else {
3101 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3102 WasArrayIndex = false;
3103 return I;
3104 }
3105 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3106 // Next subobject is a field.
3107 ObjType = FD->getType();
3108 else
3109 // Next subobject is a base class.
3110 ObjType = QualType();
3111 }
3112 }
3113 WasArrayIndex = false;
3114 return I;
3115}
3116
3117/// Determine whether the given subobject designators refer to elements of the
3118/// same array object.
3119static bool AreElementsOfSameArray(QualType ObjType,
3120 const SubobjectDesignator &A,
3121 const SubobjectDesignator &B) {
3122 if (A.Entries.size() != B.Entries.size())
3123 return false;
3124
George Burgess IVa51c4072015-10-16 01:49:01 +00003125 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003126 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3127 // A is a subobject of the array element.
3128 return false;
3129
3130 // If A (and B) designates an array element, the last entry will be the array
3131 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3132 // of length 1' case, and the entire path must match.
3133 bool WasArrayIndex;
3134 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3135 return CommonLength >= A.Entries.size() - IsArray;
3136}
3137
Richard Smith3229b742013-05-05 21:17:10 +00003138/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003139static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3140 AccessKinds AK, const LValue &LVal,
3141 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00003142 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003143 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003144 return CompleteObject();
3145 }
3146
Craig Topper36250ad2014-05-12 05:36:57 +00003147 CallStackFrame *Frame = nullptr;
Richard Smith37be3362019-05-04 04:00:45 +00003148 unsigned Depth = 0;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003149 if (LVal.getLValueCallIndex()) {
Richard Smith37be3362019-05-04 04:00:45 +00003150 std::tie(Frame, Depth) =
3151 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003152 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003153 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003154 << AK << LVal.Base.is<const ValueDecl*>();
3155 NoteLValueLocation(Info, LVal.Base);
3156 return CompleteObject();
3157 }
Richard Smith3229b742013-05-05 21:17:10 +00003158 }
3159
3160 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3161 // is not a constant expression (even if the object is non-volatile). We also
3162 // apply this rule to C++98, in order to conform to the expected 'volatile'
3163 // semantics.
3164 if (LValType.isVolatileQualified()) {
3165 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003166 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003167 << AK << LValType;
3168 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003169 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003170 return CompleteObject();
3171 }
3172
3173 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003174 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003175 QualType BaseType = getType(LVal.Base);
Richard Smith9defb7d2018-02-21 03:38:30 +00003176 bool LifetimeStartedInEvaluation = Frame;
Richard Smith3229b742013-05-05 21:17:10 +00003177
3178 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3179 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3180 // In C++11, constexpr, non-volatile variables initialized with constant
3181 // expressions are constant expressions too. Inside constexpr functions,
3182 // parameters are constant expressions even if they're non-const.
3183 // In C++1y, objects local to a constant expression (those with a Frame) are
3184 // both readable and writable inside constant expressions.
3185 // In C, such things can also be folded, although they are not ICEs.
3186 const VarDecl *VD = dyn_cast<VarDecl>(D);
3187 if (VD) {
3188 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3189 VD = VDef;
3190 }
3191 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003192 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003193 return CompleteObject();
3194 }
3195
3196 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003197 if (BaseType.isVolatileQualified()) {
3198 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003199 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003200 << AK << 1 << VD;
3201 Info.Note(VD->getLocation(), diag::note_declared_at);
3202 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003203 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003204 }
3205 return CompleteObject();
3206 }
3207
3208 // Unless we're looking at a local variable or argument in a constexpr call,
3209 // the variable we're reading must be const.
3210 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003211 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003212 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3213 // OK, we can read and modify an object if we're in the process of
3214 // evaluating its initializer, because its lifetime began in this
3215 // evaluation.
3216 } else if (AK != AK_Read) {
3217 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003218 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003219 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003220 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003221 // OK, we can read this variable.
3222 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003223 // In OpenCL if a variable is in constant address space it is a const value.
3224 if (!(BaseType.isConstQualified() ||
3225 (Info.getLangOpts().OpenCL &&
3226 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003227 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003228 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003229 Info.Note(VD->getLocation(), diag::note_declared_at);
3230 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003231 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003232 }
3233 return CompleteObject();
3234 }
3235 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3236 // We support folding of const floating-point types, in order to make
3237 // static const data members of such types (supported as an extension)
3238 // more useful.
3239 if (Info.getLangOpts().CPlusPlus11) {
3240 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3241 Info.Note(VD->getLocation(), diag::note_declared_at);
3242 } else {
3243 Info.CCEDiag(E);
3244 }
George Burgess IVb5316982016-12-27 05:33:20 +00003245 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3246 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3247 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003248 } else {
3249 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003250 if (Info.checkingPotentialConstantExpression() &&
3251 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3252 // The definition of this variable could be constexpr. We can't
3253 // access it right now, but may be able to in future.
3254 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003255 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003256 Info.Note(VD->getLocation(), diag::note_declared_at);
3257 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003258 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003259 }
3260 return CompleteObject();
3261 }
3262 }
3263
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003264 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003265 return CompleteObject();
3266 } else {
3267 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3268
3269 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003270 if (const MaterializeTemporaryExpr *MTE =
3271 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3272 assert(MTE->getStorageDuration() == SD_Static &&
3273 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003274
Richard Smithe6c01442013-06-05 00:46:14 +00003275 // Per C++1y [expr.const]p2:
3276 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3277 // - a [...] glvalue of integral or enumeration type that refers to
3278 // a non-volatile const object [...]
3279 // [...]
3280 // - a [...] glvalue of literal type that refers to a non-volatile
3281 // object whose lifetime began within the evaluation of e.
3282 //
3283 // C++11 misses the 'began within the evaluation of e' check and
3284 // instead allows all temporaries, including things like:
3285 // int &&r = 1;
3286 // int x = ++r;
3287 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003288 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003289 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3290 const ValueDecl *ED = MTE->getExtendingDecl();
3291 if (!(BaseType.isConstQualified() &&
3292 BaseType->isIntegralOrEnumerationType()) &&
3293 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003294 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003295 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3296 return CompleteObject();
3297 }
3298
3299 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3300 assert(BaseVal && "got reference to unevaluated temporary");
Richard Smith9defb7d2018-02-21 03:38:30 +00003301 LifetimeStartedInEvaluation = true;
Richard Smithe6c01442013-06-05 00:46:14 +00003302 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003303 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003304 return CompleteObject();
3305 }
3306 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003307 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003308 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003309 }
Richard Smith3229b742013-05-05 21:17:10 +00003310
3311 // Volatile temporary objects cannot be accessed in constant expressions.
3312 if (BaseType.isVolatileQualified()) {
3313 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003314 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003315 << AK << 0;
3316 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3317 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003318 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003319 }
3320 return CompleteObject();
3321 }
3322 }
3323
Richard Smith7525ff62013-05-09 07:14:00 +00003324 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003325 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003326 // object under construction.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003327 if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3328 LVal.getLValueCallIndex(),
3329 LVal.getLValueVersion())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003330 BaseType = Info.Ctx.getCanonicalType(BaseType);
3331 BaseType.removeLocalConst();
Richard Smith9defb7d2018-02-21 03:38:30 +00003332 LifetimeStartedInEvaluation = true;
Richard Smith7525ff62013-05-09 07:14:00 +00003333 }
3334
Richard Smith9defb7d2018-02-21 03:38:30 +00003335 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003336 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003337 //
3338 // FIXME: Not all local state is mutable. Allow local constant subobjects
3339 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003340 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3341 Info.EvalStatus.HasSideEffects) ||
Richard Smith37be3362019-05-04 04:00:45 +00003342 (AK != AK_Read && Depth < Info.SpeculativeEvaluationDepth))
Richard Smith3229b742013-05-05 21:17:10 +00003343 return CompleteObject();
3344
Richard Smith9defb7d2018-02-21 03:38:30 +00003345 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
Richard Smith3229b742013-05-05 21:17:10 +00003346}
3347
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003348/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003349/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3350/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003351///
3352/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003353/// \param Conv - The expression for which we are performing the conversion.
3354/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003355/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3356/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003357/// \param LVal - The glvalue on which we are attempting to perform this action.
3358/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003359static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003360 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003361 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003362 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003363 return false;
3364
Richard Smith3229b742013-05-05 21:17:10 +00003365 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003366 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003367 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003368 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3369 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3370 // initializer until now for such expressions. Such an expression can't be
3371 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003372 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003373 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003374 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003375 }
Richard Smith3229b742013-05-05 21:17:10 +00003376 APValue Lit;
3377 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3378 return false;
Richard Smith9defb7d2018-02-21 03:38:30 +00003379 CompleteObject LitObj(&Lit, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003380 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003381 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00003382 // Special-case character extraction so we don't have to construct an
3383 // APValue for the whole string.
Eli Friedman041adb02019-02-09 02:22:17 +00003384 assert(LVal.Designator.Entries.size() <= 1 &&
Eli Friedman3bf72d72019-02-08 21:18:46 +00003385 "Can only read characters from string literals");
Eli Friedman041adb02019-02-09 02:22:17 +00003386 if (LVal.Designator.Entries.empty()) {
3387 // Fail for now for LValue to RValue conversion of an array.
3388 // (This shouldn't show up in C/C++, but it could be triggered by a
3389 // weird EvaluateAsRValue call from a tool.)
3390 Info.FFDiag(Conv);
3391 return false;
3392 }
Eli Friedman3bf72d72019-02-08 21:18:46 +00003393 if (LVal.Designator.isOnePastTheEnd()) {
3394 if (Info.getLangOpts().CPlusPlus11)
3395 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
3396 else
3397 Info.FFDiag(Conv);
3398 return false;
3399 }
3400 uint64_t CharIndex = LVal.Designator.Entries[0].ArrayIndex;
3401 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3402 return true;
Richard Smith96e0c102011-11-04 02:25:55 +00003403 }
Richard Smith11562c52011-10-28 17:51:58 +00003404 }
3405
Richard Smith3229b742013-05-05 21:17:10 +00003406 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3407 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003408}
3409
3410/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003411static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003412 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003413 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003414 return false;
3415
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003416 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003417 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003418 return false;
3419 }
3420
Richard Smith3229b742013-05-05 21:17:10 +00003421 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003422 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3423}
3424
3425namespace {
3426struct CompoundAssignSubobjectHandler {
3427 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003428 const Expr *E;
3429 QualType PromotedLHSType;
3430 BinaryOperatorKind Opcode;
3431 const APValue &RHS;
3432
3433 static const AccessKinds AccessKind = AK_Assign;
3434
3435 typedef bool result_type;
3436
3437 bool checkConst(QualType QT) {
3438 // Assigning to a const object has undefined behavior.
3439 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003440 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003441 return false;
3442 }
3443 return true;
3444 }
3445
3446 bool failed() { return false; }
3447 bool found(APValue &Subobj, QualType SubobjType) {
3448 switch (Subobj.getKind()) {
3449 case APValue::Int:
3450 return found(Subobj.getInt(), SubobjType);
3451 case APValue::Float:
3452 return found(Subobj.getFloat(), SubobjType);
3453 case APValue::ComplexInt:
3454 case APValue::ComplexFloat:
3455 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003456 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003457 return false;
3458 case APValue::LValue:
3459 return foundPointer(Subobj, SubobjType);
3460 default:
3461 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003462 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003463 return false;
3464 }
3465 }
3466 bool found(APSInt &Value, QualType SubobjType) {
3467 if (!checkConst(SubobjType))
3468 return false;
3469
Tan S. B.9f935e82018-12-18 07:38:06 +00003470 if (!SubobjType->isIntegerType()) {
Richard Smith43e77732013-05-07 04:50:00 +00003471 // We don't support compound assignment on integer-cast-to-pointer
3472 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003473 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003474 return false;
3475 }
3476
Tan S. B.9f935e82018-12-18 07:38:06 +00003477 if (RHS.isInt()) {
3478 APSInt LHS =
3479 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3480 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3481 return false;
3482 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3483 return true;
3484 } else if (RHS.isFloat()) {
3485 APFloat FValue(0.0);
3486 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3487 FValue) &&
3488 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3489 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3490 Value);
3491 }
3492
3493 Info.FFDiag(E);
3494 return false;
Richard Smith43e77732013-05-07 04:50:00 +00003495 }
3496 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003497 return checkConst(SubobjType) &&
3498 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3499 Value) &&
3500 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3501 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003502 }
3503 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3504 if (!checkConst(SubobjType))
3505 return false;
3506
3507 QualType PointeeType;
3508 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3509 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003510
3511 if (PointeeType.isNull() || !RHS.isInt() ||
3512 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003513 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003514 return false;
3515 }
3516
Richard Smithd6cc1982017-01-31 02:23:02 +00003517 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003518 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003519 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003520
3521 LValue LVal;
3522 LVal.setFrom(Info.Ctx, Subobj);
3523 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3524 return false;
3525 LVal.moveInto(Subobj);
3526 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003527 }
Richard Smith43e77732013-05-07 04:50:00 +00003528};
3529} // end anonymous namespace
3530
3531const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3532
3533/// Perform a compound assignment of LVal <op>= RVal.
3534static bool handleCompoundAssignment(
3535 EvalInfo &Info, const Expr *E,
3536 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3537 BinaryOperatorKind Opcode, const APValue &RVal) {
3538 if (LVal.Designator.Invalid)
3539 return false;
3540
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003541 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003542 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003543 return false;
3544 }
3545
3546 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3547 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3548 RVal };
3549 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3550}
3551
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003552namespace {
3553struct IncDecSubobjectHandler {
3554 EvalInfo &Info;
3555 const UnaryOperator *E;
3556 AccessKinds AccessKind;
3557 APValue *Old;
3558
Richard Smith243ef902013-05-05 23:31:59 +00003559 typedef bool result_type;
3560
3561 bool checkConst(QualType QT) {
3562 // Assigning to a const object has undefined behavior.
3563 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003564 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003565 return false;
3566 }
3567 return true;
3568 }
3569
3570 bool failed() { return false; }
3571 bool found(APValue &Subobj, QualType SubobjType) {
3572 // Stash the old value. Also clear Old, so we don't clobber it later
3573 // if we're post-incrementing a complex.
3574 if (Old) {
3575 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003576 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003577 }
3578
3579 switch (Subobj.getKind()) {
3580 case APValue::Int:
3581 return found(Subobj.getInt(), SubobjType);
3582 case APValue::Float:
3583 return found(Subobj.getFloat(), SubobjType);
3584 case APValue::ComplexInt:
3585 return found(Subobj.getComplexIntReal(),
3586 SubobjType->castAs<ComplexType>()->getElementType()
3587 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3588 case APValue::ComplexFloat:
3589 return found(Subobj.getComplexFloatReal(),
3590 SubobjType->castAs<ComplexType>()->getElementType()
3591 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3592 case APValue::LValue:
3593 return foundPointer(Subobj, SubobjType);
3594 default:
3595 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003596 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003597 return false;
3598 }
3599 }
3600 bool found(APSInt &Value, QualType SubobjType) {
3601 if (!checkConst(SubobjType))
3602 return false;
3603
3604 if (!SubobjType->isIntegerType()) {
3605 // We don't support increment / decrement on integer-cast-to-pointer
3606 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003607 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003608 return false;
3609 }
3610
3611 if (Old) *Old = APValue(Value);
3612
3613 // bool arithmetic promotes to int, and the conversion back to bool
3614 // doesn't reduce mod 2^n, so special-case it.
3615 if (SubobjType->isBooleanType()) {
3616 if (AccessKind == AK_Increment)
3617 Value = 1;
3618 else
3619 Value = !Value;
3620 return true;
3621 }
3622
3623 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003624 if (AccessKind == AK_Increment) {
3625 ++Value;
3626
3627 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3628 APSInt ActualValue(Value, /*IsUnsigned*/true);
3629 return HandleOverflow(Info, E, ActualValue, SubobjType);
3630 }
3631 } else {
3632 --Value;
3633
3634 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3635 unsigned BitWidth = Value.getBitWidth();
3636 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3637 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003638 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003639 }
3640 }
3641 return true;
3642 }
3643 bool found(APFloat &Value, QualType SubobjType) {
3644 if (!checkConst(SubobjType))
3645 return false;
3646
3647 if (Old) *Old = APValue(Value);
3648
3649 APFloat One(Value.getSemantics(), 1);
3650 if (AccessKind == AK_Increment)
3651 Value.add(One, APFloat::rmNearestTiesToEven);
3652 else
3653 Value.subtract(One, APFloat::rmNearestTiesToEven);
3654 return true;
3655 }
3656 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3657 if (!checkConst(SubobjType))
3658 return false;
3659
3660 QualType PointeeType;
3661 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3662 PointeeType = PT->getPointeeType();
3663 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003664 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003665 return false;
3666 }
3667
3668 LValue LVal;
3669 LVal.setFrom(Info.Ctx, Subobj);
3670 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3671 AccessKind == AK_Increment ? 1 : -1))
3672 return false;
3673 LVal.moveInto(Subobj);
3674 return true;
3675 }
Richard Smith243ef902013-05-05 23:31:59 +00003676};
3677} // end anonymous namespace
3678
3679/// Perform an increment or decrement on LVal.
3680static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3681 QualType LValType, bool IsIncrement, APValue *Old) {
3682 if (LVal.Designator.Invalid)
3683 return false;
3684
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003685 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003686 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003687 return false;
3688 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003689
3690 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3691 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3692 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3693 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3694}
3695
Richard Smithe97cbd72011-11-11 04:05:33 +00003696/// Build an lvalue for the object argument of a member function call.
3697static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3698 LValue &This) {
3699 if (Object->getType()->isPointerType())
3700 return EvaluatePointer(Object, This, Info);
3701
3702 if (Object->isGLValue())
3703 return EvaluateLValue(Object, This, Info);
3704
Richard Smithd9f663b2013-04-22 15:31:51 +00003705 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003706 return EvaluateTemporary(Object, This, Info);
3707
Faisal Valie690b7a2016-07-02 22:34:24 +00003708 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003709 return false;
3710}
3711
3712/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3713/// lvalue referring to the result.
3714///
3715/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003716/// \param LV - An lvalue referring to the base of the member pointer.
3717/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003718/// \param IncludeMember - Specifies whether the member itself is included in
3719/// the resulting LValue subobject designator. This is not possible when
3720/// creating a bound member function.
3721/// \return The field or method declaration to which the member pointer refers,
3722/// or 0 if evaluation fails.
3723static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003724 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003725 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003726 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003727 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003728 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003729 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003730 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003731
3732 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3733 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003734 if (!MemPtr.getDecl()) {
3735 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003736 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003737 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003738 }
Richard Smith253c2a32012-01-27 01:14:48 +00003739
Richard Smith027bf112011-11-17 22:56:20 +00003740 if (MemPtr.isDerivedMember()) {
3741 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003742 // The end of the derived-to-base path for the base object must match the
3743 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003744 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003745 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003746 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003747 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003748 }
Richard Smith027bf112011-11-17 22:56:20 +00003749 unsigned PathLengthToMember =
3750 LV.Designator.Entries.size() - MemPtr.Path.size();
3751 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3752 const CXXRecordDecl *LVDecl = getAsBaseClass(
3753 LV.Designator.Entries[PathLengthToMember + I]);
3754 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003755 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003756 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003757 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003758 }
Richard Smith027bf112011-11-17 22:56:20 +00003759 }
3760
3761 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003762 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003763 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003764 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003765 } else if (!MemPtr.Path.empty()) {
3766 // Extend the LValue path with the member pointer's path.
3767 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3768 MemPtr.Path.size() + IncludeMember);
3769
3770 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003771 if (const PointerType *PT = LVType->getAs<PointerType>())
3772 LVType = PT->getPointeeType();
3773 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3774 assert(RD && "member pointer access on non-class-type expression");
3775 // The first class in the path is that of the lvalue.
3776 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3777 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003778 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003779 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003780 RD = Base;
3781 }
3782 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003783 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3784 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003785 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003786 }
3787
3788 // Add the member. Note that we cannot build bound member functions here.
3789 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003790 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003791 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003792 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003793 } else if (const IndirectFieldDecl *IFD =
3794 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003795 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003796 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003797 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003798 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003799 }
Richard Smith027bf112011-11-17 22:56:20 +00003800 }
3801
3802 return MemPtr.getDecl();
3803}
3804
Richard Smith84401042013-06-03 05:03:02 +00003805static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3806 const BinaryOperator *BO,
3807 LValue &LV,
3808 bool IncludeMember = true) {
3809 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3810
3811 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003812 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003813 MemberPtr MemPtr;
3814 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3815 }
Craig Topper36250ad2014-05-12 05:36:57 +00003816 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003817 }
3818
3819 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3820 BO->getRHS(), IncludeMember);
3821}
3822
Richard Smith027bf112011-11-17 22:56:20 +00003823/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3824/// the provided lvalue, which currently refers to the base object.
3825static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3826 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003827 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003828 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003829 return false;
3830
Richard Smitha8105bc2012-01-06 16:39:00 +00003831 QualType TargetQT = E->getType();
3832 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3833 TargetQT = PT->getPointeeType();
3834
3835 // Check this cast lands within the final derived-to-base subobject path.
3836 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003837 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003838 << D.MostDerivedType << TargetQT;
3839 return false;
3840 }
3841
Richard Smith027bf112011-11-17 22:56:20 +00003842 // Check the type of the final cast. We don't need to check the path,
3843 // since a cast can only be formed if the path is unique.
3844 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003845 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3846 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003847 if (NewEntriesSize == D.MostDerivedPathLength)
3848 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3849 else
Richard Smith027bf112011-11-17 22:56:20 +00003850 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003851 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003852 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003853 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003854 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003855 }
Richard Smith027bf112011-11-17 22:56:20 +00003856
3857 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003858 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003859}
3860
Mike Stump876387b2009-10-27 22:09:17 +00003861namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003862enum EvalStmtResult {
3863 /// Evaluation failed.
3864 ESR_Failed,
3865 /// Hit a 'return' statement.
3866 ESR_Returned,
3867 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003868 ESR_Succeeded,
3869 /// Hit a 'continue' statement.
3870 ESR_Continue,
3871 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003872 ESR_Break,
3873 /// Still scanning for 'case' or 'default' statement.
3874 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003875};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003876}
Richard Smith254a73d2011-10-28 22:34:42 +00003877
Richard Smith97fcf4b2016-08-14 23:15:52 +00003878static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3879 // We don't need to evaluate the initializer for a static local.
3880 if (!VD->hasLocalStorage())
3881 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003882
Richard Smith97fcf4b2016-08-14 23:15:52 +00003883 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003884 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00003885
Richard Smith97fcf4b2016-08-14 23:15:52 +00003886 const Expr *InitE = VD->getInit();
3887 if (!InitE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003888 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
3889 << false << VD->getType();
Richard Smith97fcf4b2016-08-14 23:15:52 +00003890 Val = APValue();
3891 return false;
3892 }
Richard Smith51f03172013-06-20 03:00:05 +00003893
Richard Smith97fcf4b2016-08-14 23:15:52 +00003894 if (InitE->isValueDependent())
3895 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003896
Richard Smith97fcf4b2016-08-14 23:15:52 +00003897 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3898 // Wipe out any partially-computed value, to allow tracking that this
3899 // evaluation failed.
3900 Val = APValue();
3901 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003902 }
3903
3904 return true;
3905}
3906
Richard Smith97fcf4b2016-08-14 23:15:52 +00003907static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3908 bool OK = true;
3909
3910 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3911 OK &= EvaluateVarDecl(Info, VD);
3912
3913 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3914 for (auto *BD : DD->bindings())
3915 if (auto *VD = BD->getHoldingVar())
3916 OK &= EvaluateDecl(Info, VD);
3917
3918 return OK;
3919}
3920
3921
Richard Smith4e18ca52013-05-06 05:56:11 +00003922/// Evaluate a condition (either a variable declaration or an expression).
3923static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3924 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003925 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003926 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3927 return false;
3928 return EvaluateAsBooleanCondition(Cond, Result, Info);
3929}
3930
Richard Smith89210072016-04-04 23:29:43 +00003931namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003932/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00003933/// statement should be stored.
3934struct StmtResult {
3935 /// The APValue that should be filled in with the returned value.
3936 APValue &Value;
3937 /// The location containing the result, if any (used to support RVO).
3938 const LValue *Slot;
3939};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003940
3941struct TempVersionRAII {
3942 CallStackFrame &Frame;
3943
3944 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3945 Frame.pushTempVersion();
3946 }
3947
3948 ~TempVersionRAII() {
3949 Frame.popTempVersion();
3950 }
3951};
3952
Richard Smith89210072016-04-04 23:29:43 +00003953}
Richard Smith52a980a2015-08-28 02:43:42 +00003954
3955static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003956 const Stmt *S,
3957 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003958
3959/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003960static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003961 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003962 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003963 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003964 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003965 case ESR_Break:
3966 return ESR_Succeeded;
3967 case ESR_Succeeded:
3968 case ESR_Continue:
3969 return ESR_Continue;
3970 case ESR_Failed:
3971 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003972 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003973 return ESR;
3974 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003975 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003976}
3977
Richard Smith496ddcf2013-05-12 17:32:42 +00003978/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003979static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003980 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003981 BlockScopeRAII Scope(Info);
3982
Richard Smith496ddcf2013-05-12 17:32:42 +00003983 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003984 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003985 {
3986 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003987 if (const Stmt *Init = SS->getInit()) {
3988 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3989 if (ESR != ESR_Succeeded)
3990 return ESR;
3991 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003992 if (SS->getConditionVariable() &&
3993 !EvaluateDecl(Info, SS->getConditionVariable()))
3994 return ESR_Failed;
3995 if (!EvaluateInteger(SS->getCond(), Value, Info))
3996 return ESR_Failed;
3997 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003998
3999 // Find the switch case corresponding to the value of the condition.
4000 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00004001 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004002 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4003 SC = SC->getNextSwitchCase()) {
4004 if (isa<DefaultStmt>(SC)) {
4005 Found = SC;
4006 continue;
4007 }
4008
4009 const CaseStmt *CS = cast<CaseStmt>(SC);
4010 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4011 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4012 : LHS;
4013 if (LHS <= Value && Value <= RHS) {
4014 Found = SC;
4015 break;
4016 }
4017 }
4018
4019 if (!Found)
4020 return ESR_Succeeded;
4021
4022 // Search the switch body for the switch case and evaluate it from there.
4023 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4024 case ESR_Break:
4025 return ESR_Succeeded;
4026 case ESR_Succeeded:
4027 case ESR_Continue:
4028 case ESR_Failed:
4029 case ESR_Returned:
4030 return ESR;
4031 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00004032 // This can only happen if the switch case is nested within a statement
4033 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004034 Info.FFDiag(Found->getBeginLoc(),
4035 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00004036 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00004037 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00004038 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00004039}
4040
Richard Smith254a73d2011-10-28 22:34:42 +00004041// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004042static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004043 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00004044 if (!Info.nextStep(S))
4045 return ESR_Failed;
4046
Richard Smith496ddcf2013-05-12 17:32:42 +00004047 // If we're hunting down a 'case' or 'default' label, recurse through
4048 // substatements until we hit the label.
4049 if (Case) {
4050 // FIXME: We don't start the lifetime of objects whose initialization we
4051 // jump over. However, such objects must be of class type with a trivial
4052 // default constructor that initialize all subobjects, so must be empty,
4053 // so this almost never matters.
4054 switch (S->getStmtClass()) {
4055 case Stmt::CompoundStmtClass:
4056 // FIXME: Precompute which substatement of a compound statement we
4057 // would jump to, and go straight there rather than performing a
4058 // linear scan each time.
4059 case Stmt::LabelStmtClass:
4060 case Stmt::AttributedStmtClass:
4061 case Stmt::DoStmtClass:
4062 break;
4063
4064 case Stmt::CaseStmtClass:
4065 case Stmt::DefaultStmtClass:
4066 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004067 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004068 break;
4069
4070 case Stmt::IfStmtClass: {
4071 // FIXME: Precompute which side of an 'if' we would jump to, and go
4072 // straight there rather than scanning both sides.
4073 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004074
4075 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4076 // preceded by our switch label.
4077 BlockScopeRAII Scope(Info);
4078
Richard Smith496ddcf2013-05-12 17:32:42 +00004079 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4080 if (ESR != ESR_CaseNotFound || !IS->getElse())
4081 return ESR;
4082 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4083 }
4084
4085 case Stmt::WhileStmtClass: {
4086 EvalStmtResult ESR =
4087 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4088 if (ESR != ESR_Continue)
4089 return ESR;
4090 break;
4091 }
4092
4093 case Stmt::ForStmtClass: {
4094 const ForStmt *FS = cast<ForStmt>(S);
4095 EvalStmtResult ESR =
4096 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4097 if (ESR != ESR_Continue)
4098 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004099 if (FS->getInc()) {
4100 FullExpressionRAII IncScope(Info);
4101 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4102 return ESR_Failed;
4103 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004104 break;
4105 }
4106
4107 case Stmt::DeclStmtClass:
4108 // FIXME: If the variable has initialization that can't be jumped over,
4109 // bail out of any immediately-surrounding compound-statement too.
4110 default:
4111 return ESR_CaseNotFound;
4112 }
4113 }
4114
Richard Smith254a73d2011-10-28 22:34:42 +00004115 switch (S->getStmtClass()) {
4116 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004117 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004118 // Don't bother evaluating beyond an expression-statement which couldn't
4119 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004120 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004121 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004122 return ESR_Failed;
4123 return ESR_Succeeded;
4124 }
4125
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004126 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004127 return ESR_Failed;
4128
4129 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004130 return ESR_Succeeded;
4131
Richard Smithd9f663b2013-04-22 15:31:51 +00004132 case Stmt::DeclStmtClass: {
4133 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004134 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004135 // Each declaration initialization is its own full-expression.
4136 // FIXME: This isn't quite right; if we're performing aggregate
4137 // initialization, each braced subexpression is its own full-expression.
4138 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00004139 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004140 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004141 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004142 return ESR_Succeeded;
4143 }
4144
Richard Smith357362d2011-12-13 06:39:58 +00004145 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004146 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004147 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004148 if (RetExpr &&
4149 !(Result.Slot
4150 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4151 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004152 return ESR_Failed;
4153 return ESR_Returned;
4154 }
Richard Smith254a73d2011-10-28 22:34:42 +00004155
4156 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004157 BlockScopeRAII Scope(Info);
4158
Richard Smith254a73d2011-10-28 22:34:42 +00004159 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004160 for (const auto *BI : CS->body()) {
4161 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004162 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004163 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004164 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004165 return ESR;
4166 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004167 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004168 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004169
4170 case Stmt::IfStmtClass: {
4171 const IfStmt *IS = cast<IfStmt>(S);
4172
4173 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004174 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004175 if (const Stmt *Init = IS->getInit()) {
4176 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4177 if (ESR != ESR_Succeeded)
4178 return ESR;
4179 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004180 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004181 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004182 return ESR_Failed;
4183
4184 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4185 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4186 if (ESR != ESR_Succeeded)
4187 return ESR;
4188 }
4189 return ESR_Succeeded;
4190 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004191
4192 case Stmt::WhileStmtClass: {
4193 const WhileStmt *WS = cast<WhileStmt>(S);
4194 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004195 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004196 bool Continue;
4197 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4198 Continue))
4199 return ESR_Failed;
4200 if (!Continue)
4201 break;
4202
4203 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4204 if (ESR != ESR_Continue)
4205 return ESR;
4206 }
4207 return ESR_Succeeded;
4208 }
4209
4210 case Stmt::DoStmtClass: {
4211 const DoStmt *DS = cast<DoStmt>(S);
4212 bool Continue;
4213 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004214 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004215 if (ESR != ESR_Continue)
4216 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004217 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004218
Richard Smith08d6a2c2013-07-24 07:11:57 +00004219 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004220 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4221 return ESR_Failed;
4222 } while (Continue);
4223 return ESR_Succeeded;
4224 }
4225
4226 case Stmt::ForStmtClass: {
4227 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004228 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004229 if (FS->getInit()) {
4230 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4231 if (ESR != ESR_Succeeded)
4232 return ESR;
4233 }
4234 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004235 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004236 bool Continue = true;
4237 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4238 FS->getCond(), Continue))
4239 return ESR_Failed;
4240 if (!Continue)
4241 break;
4242
4243 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4244 if (ESR != ESR_Continue)
4245 return ESR;
4246
Richard Smith08d6a2c2013-07-24 07:11:57 +00004247 if (FS->getInc()) {
4248 FullExpressionRAII IncScope(Info);
4249 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4250 return ESR_Failed;
4251 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004252 }
4253 return ESR_Succeeded;
4254 }
4255
Richard Smith896e0d72013-05-06 06:51:17 +00004256 case Stmt::CXXForRangeStmtClass: {
4257 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004258 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004259
Richard Smith8baa5002018-09-28 18:44:09 +00004260 // Evaluate the init-statement if present.
4261 if (FS->getInit()) {
4262 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4263 if (ESR != ESR_Succeeded)
4264 return ESR;
4265 }
4266
Richard Smith896e0d72013-05-06 06:51:17 +00004267 // Initialize the __range variable.
4268 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4269 if (ESR != ESR_Succeeded)
4270 return ESR;
4271
4272 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004273 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4274 if (ESR != ESR_Succeeded)
4275 return ESR;
4276 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004277 if (ESR != ESR_Succeeded)
4278 return ESR;
4279
4280 while (true) {
4281 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004282 {
4283 bool Continue = true;
4284 FullExpressionRAII CondExpr(Info);
4285 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4286 return ESR_Failed;
4287 if (!Continue)
4288 break;
4289 }
Richard Smith896e0d72013-05-06 06:51:17 +00004290
4291 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004292 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004293 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4294 if (ESR != ESR_Succeeded)
4295 return ESR;
4296
4297 // Loop body.
4298 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4299 if (ESR != ESR_Continue)
4300 return ESR;
4301
4302 // Increment: ++__begin
4303 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4304 return ESR_Failed;
4305 }
4306
4307 return ESR_Succeeded;
4308 }
4309
Richard Smith496ddcf2013-05-12 17:32:42 +00004310 case Stmt::SwitchStmtClass:
4311 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4312
Richard Smith4e18ca52013-05-06 05:56:11 +00004313 case Stmt::ContinueStmtClass:
4314 return ESR_Continue;
4315
4316 case Stmt::BreakStmtClass:
4317 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004318
4319 case Stmt::LabelStmtClass:
4320 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4321
4322 case Stmt::AttributedStmtClass:
4323 // As a general principle, C++11 attributes can be ignored without
4324 // any semantic impact.
4325 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4326 Case);
4327
4328 case Stmt::CaseStmtClass:
4329 case Stmt::DefaultStmtClass:
4330 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Bruno Cardoso Lopes5c1399a2018-12-10 19:03:12 +00004331 case Stmt::CXXTryStmtClass:
4332 // Evaluate try blocks by evaluating all sub statements.
4333 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004334 }
4335}
4336
Richard Smithcc36f692011-12-22 02:22:31 +00004337/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4338/// default constructor. If so, we'll fold it whether or not it's marked as
4339/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4340/// so we need special handling.
4341static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004342 const CXXConstructorDecl *CD,
4343 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004344 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4345 return false;
4346
Richard Smith66e05fe2012-01-18 05:21:49 +00004347 // Value-initialization does not call a trivial default constructor, so such a
4348 // call is a core constant expression whether or not the constructor is
4349 // constexpr.
4350 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004351 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004352 // FIXME: If DiagDecl is an implicitly-declared special member function,
4353 // we should be much more explicit about why it's not constexpr.
4354 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4355 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4356 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004357 } else {
4358 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4359 }
4360 }
4361 return true;
4362}
4363
Richard Smith357362d2011-12-13 06:39:58 +00004364/// CheckConstexprFunction - Check that a function can be called in a constant
4365/// expression.
4366static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4367 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004368 const FunctionDecl *Definition,
4369 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004370 // Potential constant expressions can contain calls to declared, but not yet
4371 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004372 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004373 Declaration->isConstexpr())
4374 return false;
4375
James Y Knightc7d3e602018-10-05 17:49:48 +00004376 // Bail out if the function declaration itself is invalid. We will
4377 // have produced a relevant diagnostic while parsing it, so just
4378 // note the problematic sub-expression.
4379 if (Declaration->isInvalidDecl()) {
4380 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004381 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004382 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004383
Richard Smith357362d2011-12-13 06:39:58 +00004384 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004385 if (Definition && Definition->isConstexpr() &&
4386 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004387 return true;
4388
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004389 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004390 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004391
Richard Smith5179eb72016-06-28 19:03:57 +00004392 // If this function is not constexpr because it is an inherited
4393 // non-constexpr constructor, diagnose that directly.
4394 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4395 if (CD && CD->isInheritingConstructor()) {
4396 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004397 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004398 DiagDecl = CD = Inherited;
4399 }
4400
4401 // FIXME: If DiagDecl is an implicitly-declared special member function
4402 // or an inheriting constructor, we should be much more explicit about why
4403 // it's not constexpr.
4404 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004405 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004406 << CD->getInheritedConstructor().getConstructor()->getParent();
4407 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004408 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004409 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004410 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4411 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004412 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004413 }
4414 return false;
4415}
4416
Richard Smithbe6dd812014-11-19 21:27:17 +00004417/// Determine if a class has any fields that might need to be copied by a
4418/// trivial copy or move operation.
4419static bool hasFields(const CXXRecordDecl *RD) {
4420 if (!RD || RD->isEmpty())
4421 return false;
4422 for (auto *FD : RD->fields()) {
4423 if (FD->isUnnamedBitfield())
4424 continue;
4425 return true;
4426 }
4427 for (auto &Base : RD->bases())
4428 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4429 return true;
4430 return false;
4431}
4432
Richard Smithd62306a2011-11-10 06:34:14 +00004433namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004434typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004435}
4436
4437/// EvaluateArgs - Evaluate the arguments to a function call.
4438static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4439 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004440 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004441 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004442 I != E; ++I) {
4443 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4444 // If we're checking for a potential constant expression, evaluate all
4445 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004446 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004447 return false;
4448 Success = false;
4449 }
4450 }
4451 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004452}
4453
Richard Smith254a73d2011-10-28 22:34:42 +00004454/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004455static bool HandleFunctionCall(SourceLocation CallLoc,
4456 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004457 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004458 EvalInfo &Info, APValue &Result,
4459 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004460 ArgVector ArgValues(Args.size());
4461 if (!EvaluateArgs(Args, ArgValues, Info))
4462 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004463
Richard Smith253c2a32012-01-27 01:14:48 +00004464 if (!Info.CheckCallLimit(CallLoc))
4465 return false;
4466
4467 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004468
4469 // For a trivial copy or move assignment, perform an APValue copy. This is
4470 // essential for unions, where the operations performed by the assignment
4471 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004472 //
4473 // Skip this for non-union classes with no fields; in that case, the defaulted
4474 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004475 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004476 if (MD && MD->isDefaulted() &&
4477 (MD->getParent()->isUnion() ||
4478 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004479 assert(This &&
4480 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4481 LValue RHS;
4482 RHS.setFrom(Info.Ctx, ArgValues[0]);
4483 APValue RHSValue;
4484 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4485 RHS, RHSValue))
4486 return false;
Brian Gesiak5488ab42019-01-11 01:54:53 +00004487 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
Richard Smith99005e62013-05-07 03:19:20 +00004488 RHSValue))
4489 return false;
4490 This->moveInto(Result);
4491 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004492 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00004493 // We're in a lambda; determine the lambda capture field maps unless we're
4494 // just constexpr checking a lambda's call operator. constexpr checking is
4495 // done before the captures have been added to the closure object (unless
4496 // we're inferring constexpr-ness), so we don't have access to them in this
4497 // case. But since we don't need the captures to constexpr check, we can
4498 // just ignore them.
4499 if (!Info.checkingPotentialConstantExpression())
4500 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4501 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004502 }
4503
Richard Smith52a980a2015-08-28 02:43:42 +00004504 StmtResult Ret = {Result, ResultSlot};
4505 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004506 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004507 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004508 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004509 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004510 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004511 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004512}
4513
Richard Smithd62306a2011-11-10 06:34:14 +00004514/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004515static bool HandleConstructorCall(const Expr *E, const LValue &This,
4516 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004517 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004518 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004519 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004520 if (!Info.CheckCallLimit(CallLoc))
4521 return false;
4522
Richard Smith3607ffe2012-02-13 03:54:03 +00004523 const CXXRecordDecl *RD = Definition->getParent();
4524 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004525 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004526 return false;
4527 }
4528
Erik Pilkington42925492017-10-04 00:18:55 +00004529 EvalInfo::EvaluatingConstructorRAII EvalObj(
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004530 Info, {This.getLValueBase(),
4531 {This.getLValueCallIndex(), This.getLValueVersion()}});
Richard Smith5179eb72016-06-28 19:03:57 +00004532 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004533
Richard Smith52a980a2015-08-28 02:43:42 +00004534 // FIXME: Creating an APValue just to hold a nonexistent return value is
4535 // wasteful.
4536 APValue RetVal;
4537 StmtResult Ret = {RetVal, nullptr};
4538
Richard Smith5179eb72016-06-28 19:03:57 +00004539 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004540 if (Definition->isDelegatingConstructor()) {
4541 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004542 {
4543 FullExpressionRAII InitScope(Info);
4544 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4545 return false;
4546 }
Richard Smith52a980a2015-08-28 02:43:42 +00004547 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004548 }
4549
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004550 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004551 // essential for unions (or classes with anonymous union members), where the
4552 // operations performed by the constructor cannot be represented by
4553 // ctor-initializers.
4554 //
4555 // Skip this for empty non-union classes; we should not perform an
4556 // lvalue-to-rvalue conversion on them because their copy constructor does not
4557 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004558 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004559 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004560 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004561 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004562 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004563 return handleLValueToRValueConversion(
4564 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4565 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004566 }
4567
4568 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004569 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004570 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004571 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004572
John McCalld7bca762012-05-01 00:38:49 +00004573 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004574 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4575
Richard Smith08d6a2c2013-07-24 07:11:57 +00004576 // A scope for temporaries lifetime-extended by reference members.
4577 BlockScopeRAII LifetimeExtendedScope(Info);
4578
Richard Smith253c2a32012-01-27 01:14:48 +00004579 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004580 unsigned BasesSeen = 0;
4581#ifndef NDEBUG
4582 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4583#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004584 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004585 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004586 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00004587 APValue *Value = &Result;
4588
4589 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004590 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004591 if (I->isBaseInitializer()) {
4592 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004593#ifndef NDEBUG
4594 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004595 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004596 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4597 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4598 "base class initializers not in expected order");
4599 ++BaseIt;
4600#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004601 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004602 BaseType->getAsCXXRecordDecl(), &Layout))
4603 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004604 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004605 } else if ((FD = I->getMember())) {
4606 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004607 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004608 if (RD->isUnion()) {
4609 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004610 Value = &Result.getUnionValue();
4611 } else {
4612 Value = &Result.getStructField(FD->getFieldIndex());
4613 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004614 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004615 // Walk the indirect field decl's chain to find the object to initialize,
4616 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004617 auto IndirectFieldChain = IFD->chain();
4618 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00004619 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004620 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4621 // Switch the union field if it differs. This happens if we had
4622 // preceding zero-initialization, and we're now initializing a union
4623 // subobject other than the first.
4624 // FIXME: In this case, the values of the other subobjects are
4625 // specified, since zero-initialization sets all padding bits to zero.
4626 if (Value->isUninit() ||
4627 (Value->isUnion() && Value->getUnionField() != FD)) {
4628 if (CD->isUnion())
4629 *Value = APValue(FD);
4630 else
4631 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004632 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004633 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004634 // Store Subobject as its parent before updating it for the last element
4635 // in the chain.
4636 if (C == IndirectFieldChain.back())
4637 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004638 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004639 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004640 if (CD->isUnion())
4641 Value = &Value->getUnionValue();
4642 else
4643 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004644 }
Richard Smithd62306a2011-11-10 06:34:14 +00004645 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004646 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004647 }
Richard Smith253c2a32012-01-27 01:14:48 +00004648
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004649 // Need to override This for implicit field initializers as in this case
4650 // This refers to innermost anonymous struct/union containing initializer,
4651 // not to currently constructed class.
4652 const Expr *Init = I->getInit();
4653 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4654 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00004655 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004656 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4657 (FD && FD->isBitField() &&
4658 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004659 // If we're checking for a potential constant expression, evaluate all
4660 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004661 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004662 return false;
4663 Success = false;
4664 }
Richard Smithd62306a2011-11-10 06:34:14 +00004665 }
4666
Richard Smithd9f663b2013-04-22 15:31:51 +00004667 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004668 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004669}
4670
Richard Smith5179eb72016-06-28 19:03:57 +00004671static bool HandleConstructorCall(const Expr *E, const LValue &This,
4672 ArrayRef<const Expr*> Args,
4673 const CXXConstructorDecl *Definition,
4674 EvalInfo &Info, APValue &Result) {
4675 ArgVector ArgValues(Args.size());
4676 if (!EvaluateArgs(Args, ArgValues, Info))
4677 return false;
4678
4679 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4680 Info, Result);
4681}
4682
Eli Friedman9a156e52008-11-12 09:44:48 +00004683//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004684// Generic Evaluation
4685//===----------------------------------------------------------------------===//
4686namespace {
4687
Aaron Ballman68af21c2014-01-03 19:26:43 +00004688template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004689class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004690 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004691private:
Richard Smith52a980a2015-08-28 02:43:42 +00004692 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004693 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004694 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004695 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004696 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004697 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004698 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004699
Richard Smith17100ba2012-02-16 02:46:34 +00004700 // Check whether a conditional operator with a non-constant condition is a
4701 // potential constant expression. If neither arm is a potential constant
4702 // expression, then the conditional operator is not either.
4703 template<typename ConditionalOperator>
4704 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004705 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004706
4707 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004708 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004709 {
Richard Smith17100ba2012-02-16 02:46:34 +00004710 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004711 StmtVisitorTy::Visit(E->getFalseExpr());
4712 if (Diag.empty())
4713 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004714 }
Richard Smith17100ba2012-02-16 02:46:34 +00004715
George Burgess IV8c892b52016-05-25 22:31:54 +00004716 {
4717 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004718 Diag.clear();
4719 StmtVisitorTy::Visit(E->getTrueExpr());
4720 if (Diag.empty())
4721 return;
4722 }
4723
4724 Error(E, diag::note_constexpr_conditional_never_const);
4725 }
4726
4727
4728 template<typename ConditionalOperator>
4729 bool HandleConditionalOperator(const ConditionalOperator *E) {
4730 bool BoolResult;
4731 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004732 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004733 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004734 return false;
4735 }
4736 if (Info.noteFailure()) {
4737 StmtVisitorTy::Visit(E->getTrueExpr());
4738 StmtVisitorTy::Visit(E->getFalseExpr());
4739 }
Richard Smith17100ba2012-02-16 02:46:34 +00004740 return false;
4741 }
4742
4743 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4744 return StmtVisitorTy::Visit(EvalExpr);
4745 }
4746
Peter Collingbournee9200682011-05-13 03:29:01 +00004747protected:
4748 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004749 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004750 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4751
Richard Smith92b1ce02011-12-12 09:28:41 +00004752 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004753 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004754 }
4755
Aaron Ballman68af21c2014-01-03 19:26:43 +00004756 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004757
4758public:
4759 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4760
4761 EvalInfo &getEvalInfo() { return Info; }
4762
Richard Smithf57d8cb2011-12-09 22:58:01 +00004763 /// Report an evaluation error. This should only be called when an error is
4764 /// first discovered. When propagating an error, just return false.
4765 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004766 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004767 return false;
4768 }
4769 bool Error(const Expr *E) {
4770 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4771 }
4772
Aaron Ballman68af21c2014-01-03 19:26:43 +00004773 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004774 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004775 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004776 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004777 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004778 }
4779
Bill Wendling8003edc2018-11-09 00:41:36 +00004780 bool VisitConstantExpr(const ConstantExpr *E)
4781 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004782 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004783 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004784 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004785 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004786 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004787 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004788 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004789 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004790 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004791 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004792 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004793 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004794 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4795 TempVersionRAII RAII(*Info.CurrentCall);
4796 return StmtVisitorTy::Visit(E->getExpr());
4797 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004798 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004799 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00004800 // The initializer may not have been parsed yet, or might be erroneous.
4801 if (!E->getExpr())
4802 return Error(E);
4803 return StmtVisitorTy::Visit(E->getExpr());
4804 }
Richard Smith5894a912011-12-19 22:12:41 +00004805 // We cannot create any objects for which cleanups are required, so there is
4806 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004807 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004808 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004809
Aaron Ballman68af21c2014-01-03 19:26:43 +00004810 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004811 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4812 return static_cast<Derived*>(this)->VisitCastExpr(E);
4813 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004814 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004815 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4816 return static_cast<Derived*>(this)->VisitCastExpr(E);
4817 }
4818
Aaron Ballman68af21c2014-01-03 19:26:43 +00004819 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004820 switch (E->getOpcode()) {
4821 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004822 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004823
4824 case BO_Comma:
4825 VisitIgnoredValue(E->getLHS());
4826 return StmtVisitorTy::Visit(E->getRHS());
4827
4828 case BO_PtrMemD:
4829 case BO_PtrMemI: {
4830 LValue Obj;
4831 if (!HandleMemberPointerAccess(Info, E, Obj))
4832 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004833 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004834 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004835 return false;
4836 return DerivedSuccess(Result, E);
4837 }
4838 }
4839 }
4840
Aaron Ballman68af21c2014-01-03 19:26:43 +00004841 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004842 // Evaluate and cache the common expression. We treat it as a temporary,
4843 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004844 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004845 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004846 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004847
Richard Smith17100ba2012-02-16 02:46:34 +00004848 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004849 }
4850
Aaron Ballman68af21c2014-01-03 19:26:43 +00004851 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004852 bool IsBcpCall = false;
4853 // If the condition (ignoring parens) is a __builtin_constant_p call,
4854 // the result is a constant expression if it can be folded without
4855 // side-effects. This is an important GNU extension. See GCC PR38377
4856 // for discussion.
4857 if (const CallExpr *CallCE =
4858 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004859 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004860 IsBcpCall = true;
4861
4862 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4863 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004864 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004865 return false;
4866
Richard Smith6d4c6582013-11-05 22:18:15 +00004867 FoldConstant Fold(Info, IsBcpCall);
4868 if (!HandleConditionalOperator(E)) {
4869 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004870 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004871 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004872
4873 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004874 }
4875
Aaron Ballman68af21c2014-01-03 19:26:43 +00004876 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004877 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00004878 return DerivedSuccess(*Value, E);
4879
4880 const Expr *Source = E->getSourceExpr();
4881 if (!Source)
4882 return Error(E);
4883 if (Source == E) { // sanity checking.
4884 assert(0 && "OpaqueValueExpr recursively refers to itself");
4885 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004886 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004887 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004888 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004889
Aaron Ballman68af21c2014-01-03 19:26:43 +00004890 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004891 APValue Result;
4892 if (!handleCallExpr(E, Result, nullptr))
4893 return false;
4894 return DerivedSuccess(Result, E);
4895 }
4896
4897 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004898 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004899 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004900 QualType CalleeType = Callee->getType();
4901
Craig Topper36250ad2014-05-12 05:36:57 +00004902 const FunctionDecl *FD = nullptr;
4903 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004904 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004905 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004906
Richard Smithe97cbd72011-11-11 04:05:33 +00004907 // Extract function decl and 'this' pointer from the callee.
4908 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004909 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004910 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4911 // Explicit bound member calls, such as x.f() or p->g();
4912 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004913 return false;
4914 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004915 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004916 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004917 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4918 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004919 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4920 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004921 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004922 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004923 return Error(Callee);
4924
4925 FD = dyn_cast<FunctionDecl>(Member);
4926 if (!FD)
4927 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004928 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004929 LValue Call;
4930 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004931 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004932
Richard Smitha8105bc2012-01-06 16:39:00 +00004933 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004934 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004935 FD = dyn_cast_or_null<FunctionDecl>(
4936 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004937 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004938 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004939 // Don't call function pointers which have been cast to some other type.
4940 // Per DR (no number yet), the caller and callee can differ in noexcept.
4941 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4942 CalleeType->getPointeeType(), FD->getType())) {
4943 return Error(E);
4944 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004945
4946 // Overloaded operator calls to member functions are represented as normal
4947 // calls with '*this' as the first argument.
4948 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4949 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004950 // FIXME: When selecting an implicit conversion for an overloaded
4951 // operator delete, we sometimes try to evaluate calls to conversion
4952 // operators without a 'this' parameter!
4953 if (Args.empty())
4954 return Error(E);
4955
Nick Lewycky13073a62017-06-12 21:15:44 +00004956 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004957 return false;
4958 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004959 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00004960 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004961 // Map the static invoker for the lambda back to the call operator.
4962 // Conveniently, we don't have to slice out the 'this' argument (as is
4963 // being done for the non-static case), since a static member function
4964 // doesn't have an implicit argument passed in.
4965 const CXXRecordDecl *ClosureClass = MD->getParent();
4966 assert(
4967 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4968 "Number of captures must be zero for conversion to function-ptr");
4969
4970 const CXXMethodDecl *LambdaCallOp =
4971 ClosureClass->getLambdaCallOperator();
4972
4973 // Set 'FD', the function that will be called below, to the call
4974 // operator. If the closure object represents a generic lambda, find
4975 // the corresponding specialization of the call operator.
4976
4977 if (ClosureClass->isGenericLambda()) {
4978 assert(MD->isFunctionTemplateSpecialization() &&
4979 "A generic lambda's static-invoker function must be a "
4980 "template specialization");
4981 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4982 FunctionTemplateDecl *CallOpTemplate =
4983 LambdaCallOp->getDescribedFunctionTemplate();
4984 void *InsertPos = nullptr;
4985 FunctionDecl *CorrespondingCallOpSpecialization =
4986 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4987 assert(CorrespondingCallOpSpecialization &&
4988 "We must always have a function call operator specialization "
4989 "that corresponds to our static invoker specialization");
4990 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4991 } else
4992 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004993 }
4994
Fangrui Song6907ce22018-07-30 19:24:48 +00004995
Richard Smithe97cbd72011-11-11 04:05:33 +00004996 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004997 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004998
Richard Smith47b34932012-02-01 02:39:43 +00004999 if (This && !This->checkSubobject(Info, E, CSK_This))
5000 return false;
5001
Richard Smith3607ffe2012-02-13 03:54:03 +00005002 // DR1358 allows virtual constexpr functions in some cases. Don't allow
5003 // calls to such functions in constant expressions.
5004 if (This && !HasQualifier &&
5005 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
5006 return Error(E, diag::note_constexpr_virtual_call);
5007
Craig Topper36250ad2014-05-12 05:36:57 +00005008 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00005009 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00005010
Nick Lewycky13073a62017-06-12 21:15:44 +00005011 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
5012 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00005013 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005014 return false;
5015
Richard Smith52a980a2015-08-28 02:43:42 +00005016 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00005017 }
5018
Aaron Ballman68af21c2014-01-03 19:26:43 +00005019 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005020 return StmtVisitorTy::Visit(E->getInitializer());
5021 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005022 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00005023 if (E->getNumInits() == 0)
5024 return DerivedZeroInitialization(E);
5025 if (E->getNumInits() == 1)
5026 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00005027 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005028 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005029 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005030 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005031 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005032 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005033 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005034 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005035 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005036 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005037 }
Richard Smith4ce706a2011-10-11 21:43:33 +00005038
Richard Smithd62306a2011-11-10 06:34:14 +00005039 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00005040 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005041 assert(!E->isArrow() && "missing call to bound member function?");
5042
Richard Smith2e312c82012-03-03 22:46:17 +00005043 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00005044 if (!Evaluate(Val, Info, E->getBase()))
5045 return false;
5046
5047 QualType BaseTy = E->getBase()->getType();
5048
5049 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00005050 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005051 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00005052 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00005053 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5054
Richard Smith9defb7d2018-02-21 03:38:30 +00005055 CompleteObject Obj(&Val, BaseTy, true);
Richard Smitha8105bc2012-01-06 16:39:00 +00005056 SubobjectDesignator Designator(BaseTy);
5057 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00005058
Richard Smith3229b742013-05-05 21:17:10 +00005059 APValue Result;
5060 return extractSubobject(Info, E, Obj, Designator, Result) &&
5061 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00005062 }
5063
Aaron Ballman68af21c2014-01-03 19:26:43 +00005064 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005065 switch (E->getCastKind()) {
5066 default:
5067 break;
5068
Richard Smitha23ab512013-05-23 00:30:41 +00005069 case CK_AtomicToNonAtomic: {
5070 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00005071 // This does not need to be done in place even for class/array types:
5072 // atomic-to-non-atomic conversion implies copying the object
5073 // representation.
5074 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00005075 return false;
5076 return DerivedSuccess(AtomicVal, E);
5077 }
5078
Richard Smith11562c52011-10-28 17:51:58 +00005079 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00005080 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00005081 return StmtVisitorTy::Visit(E->getSubExpr());
5082
5083 case CK_LValueToRValue: {
5084 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005085 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5086 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005087 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00005088 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00005089 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00005090 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005091 return false;
5092 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00005093 }
5094 }
5095
Richard Smithf57d8cb2011-12-09 22:58:01 +00005096 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005097 }
5098
Aaron Ballman68af21c2014-01-03 19:26:43 +00005099 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005100 return VisitUnaryPostIncDec(UO);
5101 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005102 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005103 return VisitUnaryPostIncDec(UO);
5104 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005105 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005106 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005107 return Error(UO);
5108
5109 LValue LVal;
5110 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5111 return false;
5112 APValue RVal;
5113 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5114 UO->isIncrementOp(), &RVal))
5115 return false;
5116 return DerivedSuccess(RVal, UO);
5117 }
5118
Aaron Ballman68af21c2014-01-03 19:26:43 +00005119 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00005120 // We will have checked the full-expressions inside the statement expression
5121 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00005122 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00005123 return Error(E);
5124
Richard Smith08d6a2c2013-07-24 07:11:57 +00005125 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00005126 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005127 if (CS->body_empty())
5128 return true;
5129
Richard Smith51f03172013-06-20 03:00:05 +00005130 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5131 BE = CS->body_end();
5132 /**/; ++BI) {
5133 if (BI + 1 == BE) {
5134 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5135 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005136 Info.FFDiag((*BI)->getBeginLoc(),
5137 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005138 return false;
5139 }
5140 return this->Visit(FinalExpr);
5141 }
5142
5143 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00005144 StmtResult Result = { ReturnValue, nullptr };
5145 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00005146 if (ESR != ESR_Succeeded) {
5147 // FIXME: If the statement-expression terminated due to 'return',
5148 // 'break', or 'continue', it would be nice to propagate that to
5149 // the outer statement evaluation rather than bailing out.
5150 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005151 Info.FFDiag((*BI)->getBeginLoc(),
5152 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005153 return false;
5154 }
5155 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005156
5157 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00005158 }
5159
Richard Smith4a678122011-10-24 18:44:57 +00005160 /// Visit a value which is evaluated, but whose value is ignored.
5161 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00005162 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00005163 }
David Majnemere9807b22016-02-26 04:23:19 +00005164
5165 /// Potentially visit a MemberExpr's base expression.
5166 void VisitIgnoredBaseExpression(const Expr *E) {
5167 // While MSVC doesn't evaluate the base expression, it does diagnose the
5168 // presence of side-effecting behavior.
5169 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5170 return;
5171 VisitIgnoredValue(E);
5172 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005173};
5174
Eric Fiselier0683c0e2018-05-07 21:07:10 +00005175} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00005176
5177//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005178// Common base class for lvalue and temporary evaluation.
5179//===----------------------------------------------------------------------===//
5180namespace {
5181template<class Derived>
5182class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005183 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00005184protected:
5185 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005186 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00005187 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005188 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00005189
5190 bool Success(APValue::LValueBase B) {
5191 Result.set(B);
5192 return true;
5193 }
5194
George Burgess IVf9013bf2017-02-10 22:52:29 +00005195 bool evaluatePointer(const Expr *E, LValue &Result) {
5196 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5197 }
5198
Richard Smith027bf112011-11-17 22:56:20 +00005199public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005200 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5201 : ExprEvaluatorBaseTy(Info), Result(Result),
5202 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005203
Richard Smith2e312c82012-03-03 22:46:17 +00005204 bool Success(const APValue &V, const Expr *E) {
5205 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005206 return true;
5207 }
Richard Smith027bf112011-11-17 22:56:20 +00005208
Richard Smith027bf112011-11-17 22:56:20 +00005209 bool VisitMemberExpr(const MemberExpr *E) {
5210 // Handle non-static data members.
5211 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005212 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005213 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005214 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005215 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005216 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005217 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005218 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005219 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005220 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005221 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005222 BaseTy = E->getBase()->getType();
5223 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005224 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005225 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005226 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005227 Result.setInvalid(E);
5228 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005229 }
Richard Smith027bf112011-11-17 22:56:20 +00005230
Richard Smith1b78b3d2012-01-25 22:15:11 +00005231 const ValueDecl *MD = E->getMemberDecl();
5232 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5233 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5234 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5235 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005236 if (!HandleLValueMember(this->Info, E, Result, FD))
5237 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005238 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005239 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5240 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005241 } else
5242 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005243
Richard Smith1b78b3d2012-01-25 22:15:11 +00005244 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005245 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005246 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005247 RefValue))
5248 return false;
5249 return Success(RefValue, E);
5250 }
5251 return true;
5252 }
5253
5254 bool VisitBinaryOperator(const BinaryOperator *E) {
5255 switch (E->getOpcode()) {
5256 default:
5257 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5258
5259 case BO_PtrMemD:
5260 case BO_PtrMemI:
5261 return HandleMemberPointerAccess(this->Info, E, Result);
5262 }
5263 }
5264
5265 bool VisitCastExpr(const CastExpr *E) {
5266 switch (E->getCastKind()) {
5267 default:
5268 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5269
5270 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005271 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005272 if (!this->Visit(E->getSubExpr()))
5273 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005274
5275 // Now figure out the necessary offset to add to the base LV to get from
5276 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005277 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5278 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005279 }
5280 }
5281};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005282}
Richard Smith027bf112011-11-17 22:56:20 +00005283
5284//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005285// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005286//
5287// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5288// function designators (in C), decl references to void objects (in C), and
5289// temporaries (if building with -Wno-address-of-temporary).
5290//
5291// LValue evaluation produces values comprising a base expression of one of the
5292// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005293// - Declarations
5294// * VarDecl
5295// * FunctionDecl
5296// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005297// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005298// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005299// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005300// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005301// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005302// * ObjCEncodeExpr
5303// * AddrLabelExpr
5304// * BlockExpr
5305// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005306// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005307// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005308// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005309// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5310// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005311// * A MaterializeTemporaryExpr that has static storage duration, with no
5312// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005313// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005314//===----------------------------------------------------------------------===//
5315namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005316class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005317 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005318public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005319 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5320 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005321
Richard Smith11562c52011-10-28 17:51:58 +00005322 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005323 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005324
Peter Collingbournee9200682011-05-13 03:29:01 +00005325 bool VisitDeclRefExpr(const DeclRefExpr *E);
5326 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005327 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005328 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5329 bool VisitMemberExpr(const MemberExpr *E);
5330 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5331 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005332 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005333 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005334 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5335 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005336 bool VisitUnaryReal(const UnaryOperator *E);
5337 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005338 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5339 return VisitUnaryPreIncDec(UO);
5340 }
5341 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5342 return VisitUnaryPreIncDec(UO);
5343 }
Richard Smith3229b742013-05-05 21:17:10 +00005344 bool VisitBinAssign(const BinaryOperator *BO);
5345 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005346
Peter Collingbournee9200682011-05-13 03:29:01 +00005347 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005348 switch (E->getCastKind()) {
5349 default:
Richard Smith027bf112011-11-17 22:56:20 +00005350 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005351
Eli Friedmance3e02a2011-10-11 00:13:24 +00005352 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005353 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005354 if (!Visit(E->getSubExpr()))
5355 return false;
5356 Result.Designator.setInvalid();
5357 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005358
Richard Smith027bf112011-11-17 22:56:20 +00005359 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005360 if (!Visit(E->getSubExpr()))
5361 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005362 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005363 }
5364 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005365};
5366} // end anonymous namespace
5367
Richard Smith11562c52011-10-28 17:51:58 +00005368/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005369/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005370/// * function designators in C, and
5371/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005372/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005373static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5374 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005375 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005376 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005377 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005378}
5379
Peter Collingbournee9200682011-05-13 03:29:01 +00005380bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005381 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005382 return Success(FD);
5383 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005384 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005385 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005386 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005387 return Error(E);
5388}
Richard Smith733237d2011-10-24 23:14:33 +00005389
Faisal Vali0528a312016-11-13 06:09:16 +00005390
Richard Smith11562c52011-10-28 17:51:58 +00005391bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005392
5393 // If we are within a lambda's call operator, check whether the 'VD' referred
5394 // to within 'E' actually represents a lambda-capture that maps to a
5395 // data-member/field within the closure object, and if so, evaluate to the
5396 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00005397 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5398 isa<DeclRefExpr>(E) &&
5399 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5400 // We don't always have a complete capture-map when checking or inferring if
5401 // the function call operator meets the requirements of a constexpr function
5402 // - but we don't need to evaluate the captures to determine constexprness
5403 // (dcl.constexpr C++17).
5404 if (Info.checkingPotentialConstantExpression())
5405 return false;
5406
Faisal Vali051e3a22017-02-16 04:12:21 +00005407 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005408 // Start with 'Result' referring to the complete closure object...
5409 Result = *Info.CurrentCall->This;
5410 // ... then update it to refer to the field of the closure object
5411 // that represents the capture.
5412 if (!HandleLValueMember(Info, E, Result, FD))
5413 return false;
5414 // And if the field is of reference type, update 'Result' to refer to what
5415 // the field refers to.
5416 if (FD->getType()->isReferenceType()) {
5417 APValue RVal;
5418 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5419 RVal))
5420 return false;
5421 Result.setFrom(Info.Ctx, RVal);
5422 }
5423 return true;
5424 }
5425 }
Craig Topper36250ad2014-05-12 05:36:57 +00005426 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005427 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5428 // Only if a local variable was declared in the function currently being
5429 // evaluated, do we expect to be able to find its value in the current
5430 // frame. (Otherwise it was likely declared in an enclosing context and
5431 // could either have a valid evaluatable value (for e.g. a constexpr
5432 // variable) or be ill-formed (and trigger an appropriate evaluation
5433 // diagnostic)).
5434 if (Info.CurrentCall->Callee &&
5435 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5436 Frame = Info.CurrentCall;
5437 }
5438 }
Richard Smith3229b742013-05-05 21:17:10 +00005439
Richard Smithfec09922011-11-01 16:57:24 +00005440 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005441 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005442 Result.set({VD, Frame->Index,
5443 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00005444 return true;
5445 }
Richard Smithce40ad62011-11-12 22:28:03 +00005446 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005447 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005448
Richard Smith3229b742013-05-05 21:17:10 +00005449 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005450 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005451 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005452 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005453 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005454 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005455 return false;
5456 }
Richard Smith3229b742013-05-05 21:17:10 +00005457 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005458}
5459
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005460bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5461 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005462 // Walk through the expression to find the materialized temporary itself.
5463 SmallVector<const Expr *, 2> CommaLHSs;
5464 SmallVector<SubobjectAdjustment, 2> Adjustments;
5465 const Expr *Inner = E->GetTemporaryExpr()->
5466 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005467
Richard Smith84401042013-06-03 05:03:02 +00005468 // If we passed any comma operators, evaluate their LHSs.
5469 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5470 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5471 return false;
5472
Richard Smithe6c01442013-06-05 00:46:14 +00005473 // A materialized temporary with static storage duration can appear within the
5474 // result of a constant expression evaluation, so we need to preserve its
5475 // value for use outside this evaluation.
5476 APValue *Value;
5477 if (E->getStorageDuration() == SD_Static) {
5478 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005479 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005480 Result.set(E);
5481 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005482 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5483 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00005484 }
5485
Richard Smithea4ad5d2013-06-06 08:19:16 +00005486 QualType Type = Inner->getType();
5487
Richard Smith84401042013-06-03 05:03:02 +00005488 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005489 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5490 (E->getStorageDuration() == SD_Static &&
5491 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5492 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005493 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005494 }
Richard Smith84401042013-06-03 05:03:02 +00005495
5496 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005497 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5498 --I;
5499 switch (Adjustments[I].Kind) {
5500 case SubobjectAdjustment::DerivedToBaseAdjustment:
5501 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5502 Type, Result))
5503 return false;
5504 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5505 break;
5506
5507 case SubobjectAdjustment::FieldAdjustment:
5508 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5509 return false;
5510 Type = Adjustments[I].Field->getType();
5511 break;
5512
5513 case SubobjectAdjustment::MemberPointerAdjustment:
5514 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5515 Adjustments[I].Ptr.RHS))
5516 return false;
5517 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5518 break;
5519 }
5520 }
5521
5522 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005523}
5524
Peter Collingbournee9200682011-05-13 03:29:01 +00005525bool
5526LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005527 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5528 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005529 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5530 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005531 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005532}
5533
Richard Smith6e525142011-12-27 12:18:28 +00005534bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005535 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005536 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005537
Faisal Valie690b7a2016-07-02 22:34:24 +00005538 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005539 << E->getExprOperand()->getType()
5540 << E->getExprOperand()->getSourceRange();
5541 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005542}
5543
Francois Pichet0066db92012-04-16 04:08:35 +00005544bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5545 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005546}
Francois Pichet0066db92012-04-16 04:08:35 +00005547
Peter Collingbournee9200682011-05-13 03:29:01 +00005548bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005549 // Handle static data members.
5550 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005551 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005552 return VisitVarDecl(E, VD);
5553 }
5554
Richard Smith254a73d2011-10-28 22:34:42 +00005555 // Handle static member functions.
5556 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5557 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005558 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005559 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005560 }
5561 }
5562
Richard Smithd62306a2011-11-10 06:34:14 +00005563 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005564 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005565}
5566
Peter Collingbournee9200682011-05-13 03:29:01 +00005567bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005568 // FIXME: Deal with vectors as array subscript bases.
5569 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005570 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005571
Nick Lewyckyad888682017-04-27 07:27:36 +00005572 bool Success = true;
5573 if (!evaluatePointer(E->getBase(), Result)) {
5574 if (!Info.noteFailure())
5575 return false;
5576 Success = false;
5577 }
Mike Stump11289f42009-09-09 15:08:12 +00005578
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005579 APSInt Index;
5580 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005581 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005582
Nick Lewyckyad888682017-04-27 07:27:36 +00005583 return Success &&
5584 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005585}
Eli Friedman9a156e52008-11-12 09:44:48 +00005586
Peter Collingbournee9200682011-05-13 03:29:01 +00005587bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005588 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005589}
5590
Richard Smith66c96992012-02-18 22:04:06 +00005591bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5592 if (!Visit(E->getSubExpr()))
5593 return false;
5594 // __real is a no-op on scalar lvalues.
5595 if (E->getSubExpr()->getType()->isAnyComplexType())
5596 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5597 return true;
5598}
5599
5600bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5601 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5602 "lvalue __imag__ on scalar?");
5603 if (!Visit(E->getSubExpr()))
5604 return false;
5605 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5606 return true;
5607}
5608
Richard Smith243ef902013-05-05 23:31:59 +00005609bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005610 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005611 return Error(UO);
5612
5613 if (!this->Visit(UO->getSubExpr()))
5614 return false;
5615
Richard Smith243ef902013-05-05 23:31:59 +00005616 return handleIncDec(
5617 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005618 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005619}
5620
5621bool LValueExprEvaluator::VisitCompoundAssignOperator(
5622 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005623 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005624 return Error(CAO);
5625
Richard Smith3229b742013-05-05 21:17:10 +00005626 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005627
5628 // The overall lvalue result is the result of evaluating the LHS.
5629 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005630 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005631 Evaluate(RHS, this->Info, CAO->getRHS());
5632 return false;
5633 }
5634
Richard Smith3229b742013-05-05 21:17:10 +00005635 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5636 return false;
5637
Richard Smith43e77732013-05-07 04:50:00 +00005638 return handleCompoundAssignment(
5639 this->Info, CAO,
5640 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5641 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005642}
5643
5644bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005645 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005646 return Error(E);
5647
Richard Smith3229b742013-05-05 21:17:10 +00005648 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005649
5650 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005651 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005652 Evaluate(NewVal, this->Info, E->getRHS());
5653 return false;
5654 }
5655
Richard Smith3229b742013-05-05 21:17:10 +00005656 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5657 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005658
5659 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005660 NewVal);
5661}
5662
Eli Friedman9a156e52008-11-12 09:44:48 +00005663//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005664// Pointer Evaluation
5665//===----------------------------------------------------------------------===//
5666
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005667/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00005668/// returned by a function with the alloc_size attribute. Returns true if we
5669/// were successful. Places an unsigned number into `Result`.
5670///
5671/// This expects the given CallExpr to be a call to a function with an
5672/// alloc_size attribute.
5673static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5674 const CallExpr *Call,
5675 llvm::APInt &Result) {
5676 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5677
Joel E. Denny81508102018-03-13 14:51:22 +00005678 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5679 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005680 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5681 if (Call->getNumArgs() <= SizeArgNo)
5682 return false;
5683
5684 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
Fangrui Song407659a2018-11-30 23:41:18 +00005685 Expr::EvalResult ExprResult;
5686 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
George Burgess IVe3763372016-12-22 02:50:20 +00005687 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00005688 Into = ExprResult.Val.getInt();
George Burgess IVe3763372016-12-22 02:50:20 +00005689 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5690 return false;
5691 Into = Into.zextOrSelf(BitsInSizeT);
5692 return true;
5693 };
5694
5695 APSInt SizeOfElem;
5696 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5697 return false;
5698
Joel E. Denny81508102018-03-13 14:51:22 +00005699 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00005700 Result = std::move(SizeOfElem);
5701 return true;
5702 }
5703
5704 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00005705 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005706 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5707 return false;
5708
5709 bool Overflow;
5710 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5711 if (Overflow)
5712 return false;
5713
5714 Result = std::move(BytesAvailable);
5715 return true;
5716}
5717
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005718/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00005719/// function.
5720static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5721 const LValue &LVal,
5722 llvm::APInt &Result) {
5723 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5724 "Can't get the size of a non alloc_size function");
5725 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5726 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5727 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5728}
5729
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005730/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00005731/// a function with the alloc_size attribute. If it was possible to do so, this
5732/// function will return true, make Result's Base point to said function call,
5733/// and mark Result's Base as invalid.
5734static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5735 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005736 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005737 return false;
5738
5739 // Because we do no form of static analysis, we only support const variables.
5740 //
5741 // Additionally, we can't support parameters, nor can we support static
5742 // variables (in the latter case, use-before-assign isn't UB; in the former,
5743 // we have no clue what they'll be assigned to).
5744 const auto *VD =
5745 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5746 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5747 return false;
5748
5749 const Expr *Init = VD->getAnyInitializer();
5750 if (!Init)
5751 return false;
5752
5753 const Expr *E = Init->IgnoreParens();
5754 if (!tryUnwrapAllocSizeCall(E))
5755 return false;
5756
5757 // Store E instead of E unwrapped so that the type of the LValue's base is
5758 // what the user wanted.
5759 Result.setInvalid(E);
5760
5761 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005762 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005763 return true;
5764}
5765
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005766namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005767class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005768 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005769 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005770 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005771
Peter Collingbournee9200682011-05-13 03:29:01 +00005772 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005773 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005774 return true;
5775 }
George Burgess IVe3763372016-12-22 02:50:20 +00005776
George Burgess IVf9013bf2017-02-10 22:52:29 +00005777 bool evaluateLValue(const Expr *E, LValue &Result) {
5778 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5779 }
5780
5781 bool evaluatePointer(const Expr *E, LValue &Result) {
5782 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5783 }
5784
George Burgess IVe3763372016-12-22 02:50:20 +00005785 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005786public:
Mike Stump11289f42009-09-09 15:08:12 +00005787
George Burgess IVf9013bf2017-02-10 22:52:29 +00005788 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5789 : ExprEvaluatorBaseTy(info), Result(Result),
5790 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005791
Richard Smith2e312c82012-03-03 22:46:17 +00005792 bool Success(const APValue &V, const Expr *E) {
5793 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005794 return true;
5795 }
Richard Smithfddd3842011-12-30 21:15:51 +00005796 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005797 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5798 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005799 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005800 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005801
John McCall45d55e42010-05-07 21:00:08 +00005802 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005803 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005804 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005805 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005806 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005807 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00005808 if (E->isExpressibleAsConstantInitializer())
5809 return Success(E);
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005810 if (Info.noteFailure())
5811 EvaluateIgnoredValue(Info, E->getSubExpr());
5812 return Error(E);
5813 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005814 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005815 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005816 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005817 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005818 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005819 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005820 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005821 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005822 }
Richard Smithd62306a2011-11-10 06:34:14 +00005823 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005824 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005825 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005826 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005827 if (!Info.CurrentCall->This) {
5828 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005829 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005830 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005831 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005832 return false;
5833 }
Richard Smithd62306a2011-11-10 06:34:14 +00005834 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005835 // If we are inside a lambda's call operator, the 'this' expression refers
5836 // to the enclosing '*this' object (either by value or reference) which is
5837 // either copied into the closure object's field that represents the '*this'
5838 // or refers to '*this'.
5839 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5840 // Update 'Result' to refer to the data member/field of the closure object
5841 // that represents the '*this' capture.
5842 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00005843 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005844 return false;
5845 // If we captured '*this' by reference, replace the field with its referent.
5846 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5847 ->isPointerType()) {
5848 APValue RVal;
5849 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5850 RVal))
5851 return false;
5852
5853 Result.setFrom(Info.Ctx, RVal);
5854 }
5855 }
Richard Smithd62306a2011-11-10 06:34:14 +00005856 return true;
5857 }
John McCallc07a0c72011-02-17 10:25:35 +00005858
Eli Friedman449fe542009-03-23 04:56:01 +00005859 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005860};
Chris Lattner05706e882008-07-11 18:11:29 +00005861} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005862
George Burgess IVf9013bf2017-02-10 22:52:29 +00005863static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5864 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005865 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005866 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005867}
5868
John McCall45d55e42010-05-07 21:00:08 +00005869bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005870 if (E->getOpcode() != BO_Add &&
5871 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005872 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005873
Chris Lattner05706e882008-07-11 18:11:29 +00005874 const Expr *PExp = E->getLHS();
5875 const Expr *IExp = E->getRHS();
5876 if (IExp->getType()->isPointerType())
5877 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005878
George Burgess IVf9013bf2017-02-10 22:52:29 +00005879 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005880 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005881 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005882
John McCall45d55e42010-05-07 21:00:08 +00005883 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005884 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005885 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005886
Richard Smith96e0c102011-11-04 02:25:55 +00005887 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005888 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005889
Ted Kremenek28831752012-08-23 20:46:57 +00005890 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005891 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005892}
Eli Friedman9a156e52008-11-12 09:44:48 +00005893
John McCall45d55e42010-05-07 21:00:08 +00005894bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005895 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005896}
Mike Stump11289f42009-09-09 15:08:12 +00005897
Richard Smith81dfef92018-07-11 00:29:05 +00005898bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5899 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005900
Eli Friedman847a2bc2009-12-27 05:43:15 +00005901 switch (E->getCastKind()) {
5902 default:
5903 break;
5904
John McCalle3027922010-08-25 11:45:40 +00005905 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005906 case CK_CPointerToObjCPointerCast:
5907 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005908 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005909 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005910 if (!Visit(SubExpr))
5911 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005912 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5913 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5914 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005915 if (!E->getType()->isVoidPointerType()) {
James Y Knight49bf3702018-10-05 21:53:51 +00005916 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005917 if (SubExpr->getType()->isVoidPointerType())
5918 CCEDiag(E, diag::note_constexpr_invalid_cast)
5919 << 3 << SubExpr->getType();
5920 else
5921 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5922 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005923 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5924 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005925 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005926
Anders Carlsson18275092010-10-31 20:41:46 +00005927 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005928 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005929 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005930 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005931 if (!Result.Base && Result.Offset.isZero())
5932 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005933
Richard Smithd62306a2011-11-10 06:34:14 +00005934 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005935 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005936 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5937 castAs<PointerType>()->getPointeeType(),
5938 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005939
Richard Smith027bf112011-11-17 22:56:20 +00005940 case CK_BaseToDerived:
5941 if (!Visit(E->getSubExpr()))
5942 return false;
5943 if (!Result.Base && Result.Offset.isZero())
5944 return true;
5945 return HandleBaseToDerivedCast(Info, E, Result);
5946
Richard Smith0b0a0b62011-10-29 20:57:55 +00005947 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005948 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005949 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005950
John McCalle3027922010-08-25 11:45:40 +00005951 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005952 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5953
Richard Smith2e312c82012-03-03 22:46:17 +00005954 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005955 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005956 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005957
John McCall45d55e42010-05-07 21:00:08 +00005958 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005959 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5960 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005961 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005962 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005963 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00005964 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005965 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005966 return true;
5967 } else {
5968 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005969 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005970 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005971 }
5972 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005973
5974 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005975 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005976 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005977 return false;
5978 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005979 APValue &Value = createTemporary(SubExpr, false, Result,
5980 *Info.CurrentCall);
5981 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005982 return false;
5983 }
Richard Smith96e0c102011-11-04 02:25:55 +00005984 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005985 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5986 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005987 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005988 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005989 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005990 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005991 }
Richard Smithdd785442011-10-31 20:57:44 +00005992
John McCalle3027922010-08-25 11:45:40 +00005993 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005994 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005995
5996 case CK_LValueToRValue: {
5997 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005998 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005999 return false;
6000
6001 APValue RVal;
6002 // Note, we use the subexpression's type in order to retain cv-qualifiers.
6003 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
6004 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00006005 return InvalidBaseOK &&
6006 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00006007 return Success(RVal, E);
6008 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006009 }
6010
Richard Smith11562c52011-10-28 17:51:58 +00006011 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00006012}
Chris Lattner05706e882008-07-11 18:11:29 +00006013
Richard Smith6822bd72018-10-26 19:26:45 +00006014static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
6015 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006016 // C++ [expr.alignof]p3:
6017 // When alignof is applied to a reference type, the result is the
6018 // alignment of the referenced type.
6019 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6020 T = Ref->getPointeeType();
6021
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00006022 if (T.getQualifiers().hasUnaligned())
6023 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00006024
6025 const bool AlignOfReturnsPreferred =
6026 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
6027
6028 // __alignof is defined to return the preferred alignment.
6029 // Before 8, clang returned the preferred alignment for alignof and _Alignof
6030 // as well.
6031 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
6032 return Info.Ctx.toCharUnitsFromBits(
6033 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
6034 // alignof and _Alignof are defined to return the ABI alignment.
6035 else if (ExprKind == UETT_AlignOf)
6036 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
6037 else
6038 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00006039}
6040
Richard Smith6822bd72018-10-26 19:26:45 +00006041static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
6042 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006043 E = E->IgnoreParens();
6044
6045 // The kinds of expressions that we have special-case logic here for
6046 // should be kept up to date with the special checks for those
6047 // expressions in Sema.
6048
6049 // alignof decl is always accepted, even if it doesn't make sense: we default
6050 // to 1 in those cases.
6051 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6052 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6053 /*RefAsPointee*/true);
6054
6055 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
6056 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6057 /*RefAsPointee*/true);
6058
Richard Smith6822bd72018-10-26 19:26:45 +00006059 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006060}
6061
George Burgess IVe3763372016-12-22 02:50:20 +00006062// To be clear: this happily visits unsupported builtins. Better name welcomed.
6063bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
6064 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
6065 return true;
6066
George Burgess IVf9013bf2017-02-10 22:52:29 +00006067 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00006068 return false;
6069
6070 Result.setInvalid(E);
6071 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00006072 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00006073 return true;
6074}
6075
Peter Collingbournee9200682011-05-13 03:29:01 +00006076bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006077 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00006078 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00006079
Richard Smith6328cbd2016-11-16 00:57:23 +00006080 if (unsigned BuiltinOp = E->getBuiltinCallee())
6081 return VisitBuiltinCallExpr(E, BuiltinOp);
6082
George Burgess IVe3763372016-12-22 02:50:20 +00006083 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006084}
6085
6086bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6087 unsigned BuiltinOp) {
6088 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00006089 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006090 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006091 case Builtin::BI__builtin_assume_aligned: {
6092 // We need to be very careful here because: if the pointer does not have the
6093 // asserted alignment, then the behavior is undefined, and undefined
6094 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00006095 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00006096 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00006097
Hal Finkel0dd05d42014-10-03 17:18:37 +00006098 LValue OffsetResult(Result);
6099 APSInt Alignment;
6100 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6101 return false;
Richard Smith642a2362017-01-30 23:30:26 +00006102 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00006103
6104 if (E->getNumArgs() > 2) {
6105 APSInt Offset;
6106 if (!EvaluateInteger(E->getArg(2), Offset, Info))
6107 return false;
6108
Richard Smith642a2362017-01-30 23:30:26 +00006109 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006110 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6111 }
6112
6113 // If there is a base object, then it must have the correct alignment.
6114 if (OffsetResult.Base) {
6115 CharUnits BaseAlignment;
6116 if (const ValueDecl *VD =
6117 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6118 BaseAlignment = Info.Ctx.getDeclAlign(VD);
6119 } else {
Richard Smith6822bd72018-10-26 19:26:45 +00006120 BaseAlignment = GetAlignOfExpr(
6121 Info, OffsetResult.Base.get<const Expr *>(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006122 }
6123
6124 if (BaseAlignment < Align) {
6125 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00006126 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00006127 CCEDiag(E->getArg(0),
6128 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00006129 << (unsigned)BaseAlignment.getQuantity()
6130 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006131 return false;
6132 }
6133 }
6134
6135 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006136 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006137 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006138
Richard Smith642a2362017-01-30 23:30:26 +00006139 (OffsetResult.Base
6140 ? CCEDiag(E->getArg(0),
6141 diag::note_constexpr_baa_insufficient_alignment) << 1
6142 : CCEDiag(E->getArg(0),
6143 diag::note_constexpr_baa_value_insufficient_alignment))
6144 << (int)OffsetResult.Offset.getQuantity()
6145 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006146 return false;
6147 }
6148
6149 return true;
6150 }
Eric Fiselier26187502018-12-14 21:11:28 +00006151 case Builtin::BI__builtin_launder:
6152 return evaluatePointer(E->getArg(0), Result);
Richard Smithe9507952016-11-12 01:39:56 +00006153 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006154 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00006155 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006156 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00006157 if (Info.getLangOpts().CPlusPlus11)
6158 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6159 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00006160 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00006161 else
6162 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006163 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00006164 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006165 case Builtin::BI__builtin_wcschr:
6166 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006167 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006168 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00006169 if (!Visit(E->getArg(0)))
6170 return false;
6171 APSInt Desired;
6172 if (!EvaluateInteger(E->getArg(1), Desired, Info))
6173 return false;
6174 uint64_t MaxLength = uint64_t(-1);
6175 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00006176 BuiltinOp != Builtin::BIwcschr &&
6177 BuiltinOp != Builtin::BI__builtin_strchr &&
6178 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00006179 APSInt N;
6180 if (!EvaluateInteger(E->getArg(2), N, Info))
6181 return false;
6182 MaxLength = N.getExtValue();
6183 }
Hubert Tong147b7432018-12-12 16:53:43 +00006184 // We cannot find the value if there are no candidates to match against.
6185 if (MaxLength == 0u)
6186 return ZeroInitialization(E);
6187 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
6188 Result.Designator.Invalid)
6189 return false;
6190 QualType CharTy = Result.Designator.getType(Info.Ctx);
6191 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
6192 BuiltinOp == Builtin::BI__builtin_memchr;
6193 assert(IsRawByte ||
6194 Info.Ctx.hasSameUnqualifiedType(
6195 CharTy, E->getArg(0)->getType()->getPointeeType()));
6196 // Pointers to const void may point to objects of incomplete type.
6197 if (IsRawByte && CharTy->isIncompleteType()) {
6198 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
6199 return false;
6200 }
6201 // Give up on byte-oriented matching against multibyte elements.
6202 // FIXME: We can compare the bytes in the correct order.
6203 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
6204 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00006205 // Figure out what value we're actually looking for (after converting to
6206 // the corresponding unsigned type if necessary).
6207 uint64_t DesiredVal;
6208 bool StopAtNull = false;
6209 switch (BuiltinOp) {
6210 case Builtin::BIstrchr:
6211 case Builtin::BI__builtin_strchr:
6212 // strchr compares directly to the passed integer, and therefore
6213 // always fails if given an int that is not a char.
6214 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6215 E->getArg(1)->getType(),
6216 Desired),
6217 Desired))
6218 return ZeroInitialization(E);
6219 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006220 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006221 case Builtin::BImemchr:
6222 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006223 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006224 // memchr compares by converting both sides to unsigned char. That's also
6225 // correct for strchr if we get this far (to cope with plain char being
6226 // unsigned in the strchr case).
6227 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6228 break;
Richard Smithe9507952016-11-12 01:39:56 +00006229
Richard Smith8110c9d2016-11-29 19:45:17 +00006230 case Builtin::BIwcschr:
6231 case Builtin::BI__builtin_wcschr:
6232 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006233 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006234 case Builtin::BIwmemchr:
6235 case Builtin::BI__builtin_wmemchr:
6236 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6237 DesiredVal = Desired.getZExtValue();
6238 break;
6239 }
Richard Smithe9507952016-11-12 01:39:56 +00006240
6241 for (; MaxLength; --MaxLength) {
6242 APValue Char;
6243 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6244 !Char.isInt())
6245 return false;
6246 if (Char.getInt().getZExtValue() == DesiredVal)
6247 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00006248 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00006249 break;
6250 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6251 return false;
6252 }
6253 // Not found: return nullptr.
6254 return ZeroInitialization(E);
6255 }
6256
Richard Smith06f71b52018-08-04 00:57:17 +00006257 case Builtin::BImemcpy:
6258 case Builtin::BImemmove:
6259 case Builtin::BIwmemcpy:
6260 case Builtin::BIwmemmove:
6261 if (Info.getLangOpts().CPlusPlus11)
6262 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6263 << /*isConstexpr*/0 << /*isConstructor*/0
6264 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6265 else
6266 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6267 LLVM_FALLTHROUGH;
6268 case Builtin::BI__builtin_memcpy:
6269 case Builtin::BI__builtin_memmove:
6270 case Builtin::BI__builtin_wmemcpy:
6271 case Builtin::BI__builtin_wmemmove: {
6272 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
6273 BuiltinOp == Builtin::BIwmemmove ||
6274 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
6275 BuiltinOp == Builtin::BI__builtin_wmemmove;
6276 bool Move = BuiltinOp == Builtin::BImemmove ||
6277 BuiltinOp == Builtin::BIwmemmove ||
6278 BuiltinOp == Builtin::BI__builtin_memmove ||
6279 BuiltinOp == Builtin::BI__builtin_wmemmove;
6280
6281 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00006282 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00006283 return false;
6284 LValue Dest = Result;
6285
6286 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00006287 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00006288 return false;
6289
6290 APSInt N;
6291 if (!EvaluateInteger(E->getArg(2), N, Info))
6292 return false;
6293 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
6294
6295 // If the size is zero, we treat this as always being a valid no-op.
6296 // (Even if one of the src and dest pointers is null.)
6297 if (!N)
6298 return true;
6299
Richard Smith128719c2018-09-13 22:47:33 +00006300 // Otherwise, if either of the operands is null, we can't proceed. Don't
6301 // try to determine the type of the copied objects, because there aren't
6302 // any.
6303 if (!Src.Base || !Dest.Base) {
6304 APValue Val;
6305 (!Src.Base ? Src : Dest).moveInto(Val);
6306 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
6307 << Move << WChar << !!Src.Base
6308 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
6309 return false;
6310 }
6311 if (Src.Designator.Invalid || Dest.Designator.Invalid)
6312 return false;
6313
Richard Smith06f71b52018-08-04 00:57:17 +00006314 // We require that Src and Dest are both pointers to arrays of
6315 // trivially-copyable type. (For the wide version, the designator will be
6316 // invalid if the designated object is not a wchar_t.)
6317 QualType T = Dest.Designator.getType(Info.Ctx);
6318 QualType SrcT = Src.Designator.getType(Info.Ctx);
6319 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
6320 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
6321 return false;
6322 }
Petr Pavlued083f22018-10-04 09:25:44 +00006323 if (T->isIncompleteType()) {
6324 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
6325 return false;
6326 }
Richard Smith06f71b52018-08-04 00:57:17 +00006327 if (!T.isTriviallyCopyableType(Info.Ctx)) {
6328 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
6329 return false;
6330 }
6331
6332 // Figure out how many T's we're copying.
6333 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
6334 if (!WChar) {
6335 uint64_t Remainder;
6336 llvm::APInt OrigN = N;
6337 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
6338 if (Remainder) {
6339 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6340 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
6341 << (unsigned)TSize;
6342 return false;
6343 }
6344 }
6345
6346 // Check that the copying will remain within the arrays, just so that we
6347 // can give a more meaningful diagnostic. This implicitly also checks that
6348 // N fits into 64 bits.
6349 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
6350 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
6351 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
6352 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6353 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
6354 << N.toString(10, /*Signed*/false);
6355 return false;
6356 }
6357 uint64_t NElems = N.getZExtValue();
6358 uint64_t NBytes = NElems * TSize;
6359
6360 // Check for overlap.
6361 int Direction = 1;
6362 if (HasSameBase(Src, Dest)) {
6363 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
6364 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
6365 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
6366 // Dest is inside the source region.
6367 if (!Move) {
6368 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6369 return false;
6370 }
6371 // For memmove and friends, copy backwards.
6372 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
6373 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
6374 return false;
6375 Direction = -1;
6376 } else if (!Move && SrcOffset >= DestOffset &&
6377 SrcOffset - DestOffset < NBytes) {
6378 // Src is inside the destination region for memcpy: invalid.
6379 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6380 return false;
6381 }
6382 }
6383
6384 while (true) {
6385 APValue Val;
6386 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
6387 !handleAssignment(Info, E, Dest, T, Val))
6388 return false;
6389 // Do not iterate past the last element; if we're copying backwards, that
6390 // might take us off the start of the array.
6391 if (--NElems == 0)
6392 return true;
6393 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
6394 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
6395 return false;
6396 }
6397 }
6398
Richard Smith6cbd65d2013-07-11 02:27:57 +00006399 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006400 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006401 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006402}
Chris Lattner05706e882008-07-11 18:11:29 +00006403
6404//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006405// Member Pointer Evaluation
6406//===----------------------------------------------------------------------===//
6407
6408namespace {
6409class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006410 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006411 MemberPtr &Result;
6412
6413 bool Success(const ValueDecl *D) {
6414 Result = MemberPtr(D);
6415 return true;
6416 }
6417public:
6418
6419 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6420 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6421
Richard Smith2e312c82012-03-03 22:46:17 +00006422 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006423 Result.setFrom(V);
6424 return true;
6425 }
Richard Smithfddd3842011-12-30 21:15:51 +00006426 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006427 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006428 }
6429
6430 bool VisitCastExpr(const CastExpr *E);
6431 bool VisitUnaryAddrOf(const UnaryOperator *E);
6432};
6433} // end anonymous namespace
6434
6435static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6436 EvalInfo &Info) {
6437 assert(E->isRValue() && E->getType()->isMemberPointerType());
6438 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6439}
6440
6441bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6442 switch (E->getCastKind()) {
6443 default:
6444 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6445
6446 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006447 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006448 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006449
6450 case CK_BaseToDerivedMemberPointer: {
6451 if (!Visit(E->getSubExpr()))
6452 return false;
6453 if (E->path_empty())
6454 return true;
6455 // Base-to-derived member pointer casts store the path in derived-to-base
6456 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6457 // the wrong end of the derived->base arc, so stagger the path by one class.
6458 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6459 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6460 PathI != PathE; ++PathI) {
6461 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6462 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6463 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006464 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006465 }
6466 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6467 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006468 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006469 return true;
6470 }
6471
6472 case CK_DerivedToBaseMemberPointer:
6473 if (!Visit(E->getSubExpr()))
6474 return false;
6475 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6476 PathE = E->path_end(); PathI != PathE; ++PathI) {
6477 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6478 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6479 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006480 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006481 }
6482 return true;
6483 }
6484}
6485
6486bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6487 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6488 // member can be formed.
6489 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6490}
6491
6492//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006493// Record Evaluation
6494//===----------------------------------------------------------------------===//
6495
6496namespace {
6497 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006498 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006499 const LValue &This;
6500 APValue &Result;
6501 public:
6502
6503 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6504 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6505
Richard Smith2e312c82012-03-03 22:46:17 +00006506 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006507 Result = V;
6508 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006509 }
Richard Smithb8348f52016-05-12 22:16:28 +00006510 bool ZeroInitialization(const Expr *E) {
6511 return ZeroInitialization(E, E->getType());
6512 }
6513 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006514
Richard Smith52a980a2015-08-28 02:43:42 +00006515 bool VisitCallExpr(const CallExpr *E) {
6516 return handleCallExpr(E, Result, &This);
6517 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006518 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006519 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006520 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6521 return VisitCXXConstructExpr(E, E->getType());
6522 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006523 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006524 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006525 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006526 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00006527
6528 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006529 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006530}
Richard Smithd62306a2011-11-10 06:34:14 +00006531
Richard Smithfddd3842011-12-30 21:15:51 +00006532/// Perform zero-initialization on an object of non-union class type.
6533/// C++11 [dcl.init]p5:
6534/// To zero-initialize an object or reference of type T means:
6535/// [...]
6536/// -- if T is a (possibly cv-qualified) non-union class type,
6537/// each non-static data member and each base-class subobject is
6538/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006539static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6540 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006541 const LValue &This, APValue &Result) {
6542 assert(!RD->isUnion() && "Expected non-union class type");
6543 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6544 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006545 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006546
John McCalld7bca762012-05-01 00:38:49 +00006547 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006548 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6549
6550 if (CD) {
6551 unsigned Index = 0;
6552 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006553 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006554 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6555 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006556 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6557 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006558 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006559 Result.getStructBase(Index)))
6560 return false;
6561 }
6562 }
6563
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006564 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006565 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006566 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006567 continue;
6568
6569 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006570 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006571 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006572
David Blaikie2d7c57e2012-04-30 02:36:29 +00006573 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006574 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006575 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006576 return false;
6577 }
6578
6579 return true;
6580}
6581
Richard Smithb8348f52016-05-12 22:16:28 +00006582bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6583 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006584 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006585 if (RD->isUnion()) {
6586 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6587 // object's first non-static named data member is zero-initialized
6588 RecordDecl::field_iterator I = RD->field_begin();
6589 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006590 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006591 return true;
6592 }
6593
6594 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006595 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006596 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006597 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006598 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006599 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006600 }
6601
Richard Smith5d108602012-02-17 00:44:16 +00006602 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006603 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006604 return false;
6605 }
6606
Richard Smitha8105bc2012-01-06 16:39:00 +00006607 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006608}
6609
Richard Smithe97cbd72011-11-11 04:05:33 +00006610bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6611 switch (E->getCastKind()) {
6612 default:
6613 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6614
6615 case CK_ConstructorConversion:
6616 return Visit(E->getSubExpr());
6617
6618 case CK_DerivedToBase:
6619 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006620 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006621 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006622 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006623 if (!DerivedObject.isStruct())
6624 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006625
6626 // Derived-to-base rvalue conversion: just slice off the derived part.
6627 APValue *Value = &DerivedObject;
6628 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6629 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6630 PathE = E->path_end(); PathI != PathE; ++PathI) {
6631 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6632 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6633 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6634 RD = Base;
6635 }
6636 Result = *Value;
6637 return true;
6638 }
6639 }
6640}
6641
Richard Smithd62306a2011-11-10 06:34:14 +00006642bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006643 if (E->isTransparent())
6644 return Visit(E->getInit(0));
6645
Richard Smithd62306a2011-11-10 06:34:14 +00006646 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006647 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006648 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6649
6650 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006651 const FieldDecl *Field = E->getInitializedFieldInUnion();
6652 Result = APValue(Field);
6653 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006654 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006655
6656 // If the initializer list for a union does not contain any elements, the
6657 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006658 // FIXME: The element should be initialized from an initializer list.
6659 // Is this difference ever observable for initializer lists which
6660 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006661 ImplicitValueInitExpr VIE(Field->getType());
6662 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6663
Richard Smithd62306a2011-11-10 06:34:14 +00006664 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006665 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6666 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006667
6668 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6669 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6670 isa<CXXDefaultInitExpr>(InitExpr));
6671
Richard Smithb228a862012-02-15 02:18:13 +00006672 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006673 }
6674
Richard Smith872307e2016-03-08 22:17:41 +00006675 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006676 if (Result.isUninit())
6677 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6678 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006679 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006680 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006681
6682 // Initialize base classes.
6683 if (CXXRD) {
6684 for (const auto &Base : CXXRD->bases()) {
6685 assert(ElementNo < E->getNumInits() && "missing init for base class");
6686 const Expr *Init = E->getInit(ElementNo);
6687
6688 LValue Subobject = This;
6689 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6690 return false;
6691
6692 APValue &FieldVal = Result.getStructBase(ElementNo);
6693 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006694 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006695 return false;
6696 Success = false;
6697 }
6698 ++ElementNo;
6699 }
6700 }
6701
6702 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006703 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006704 // Anonymous bit-fields are not considered members of the class for
6705 // purposes of aggregate initialization.
6706 if (Field->isUnnamedBitfield())
6707 continue;
6708
6709 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006710
Richard Smith253c2a32012-01-27 01:14:48 +00006711 bool HaveInit = ElementNo < E->getNumInits();
6712
6713 // FIXME: Diagnostics here should point to the end of the initializer
6714 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006715 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006716 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006717 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006718
6719 // Perform an implicit value-initialization for members beyond the end of
6720 // the initializer list.
6721 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006722 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006723
Richard Smith852c9db2013-04-20 22:23:05 +00006724 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6725 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6726 isa<CXXDefaultInitExpr>(Init));
6727
Richard Smith49ca8aa2013-08-06 07:09:20 +00006728 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6729 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6730 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006731 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006732 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006733 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006734 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006735 }
6736 }
6737
Richard Smith253c2a32012-01-27 01:14:48 +00006738 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006739}
6740
Richard Smithb8348f52016-05-12 22:16:28 +00006741bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6742 QualType T) {
6743 // Note that E's type is not necessarily the type of our class here; we might
6744 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006745 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006746 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6747
Richard Smithfddd3842011-12-30 21:15:51 +00006748 bool ZeroInit = E->requiresZeroInitialization();
6749 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006750 // If we've already performed zero-initialization, we're already done.
6751 if (!Result.isUninit())
6752 return true;
6753
Richard Smithda3f4fd2014-03-05 23:32:50 +00006754 // We can get here in two different ways:
6755 // 1) We're performing value-initialization, and should zero-initialize
6756 // the object, or
6757 // 2) We're performing default-initialization of an object with a trivial
6758 // constexpr default constructor, in which case we should start the
6759 // lifetimes of all the base subobjects (there can be no data member
6760 // subobjects in this case) per [basic.life]p1.
6761 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006762 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006763 }
6764
Craig Topper36250ad2014-05-12 05:36:57 +00006765 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006766 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006767
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006768 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006769 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006770
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006771 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006772 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006773 if (const MaterializeTemporaryExpr *ME
6774 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6775 return Visit(ME->GetTemporaryExpr());
6776
Richard Smithb8348f52016-05-12 22:16:28 +00006777 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006778 return false;
6779
Craig Topper5fc8fc22014-08-27 06:28:36 +00006780 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006781 return HandleConstructorCall(E, This, Args,
6782 cast<CXXConstructorDecl>(Definition), Info,
6783 Result);
6784}
6785
6786bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6787 const CXXInheritedCtorInitExpr *E) {
6788 if (!Info.CurrentCall) {
6789 assert(Info.checkingPotentialConstantExpression());
6790 return false;
6791 }
6792
6793 const CXXConstructorDecl *FD = E->getConstructor();
6794 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6795 return false;
6796
6797 const FunctionDecl *Definition = nullptr;
6798 auto Body = FD->getBody(Definition);
6799
6800 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6801 return false;
6802
6803 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006804 cast<CXXConstructorDecl>(Definition), Info,
6805 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006806}
6807
Richard Smithcc1b96d2013-06-12 22:31:48 +00006808bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6809 const CXXStdInitializerListExpr *E) {
6810 const ConstantArrayType *ArrayType =
6811 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6812
6813 LValue Array;
6814 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6815 return false;
6816
6817 // Get a pointer to the first element of the array.
6818 Array.addArray(Info, E, ArrayType);
6819
6820 // FIXME: Perform the checks on the field types in SemaInit.
6821 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6822 RecordDecl::field_iterator Field = Record->field_begin();
6823 if (Field == Record->field_end())
6824 return Error(E);
6825
6826 // Start pointer.
6827 if (!Field->getType()->isPointerType() ||
6828 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6829 ArrayType->getElementType()))
6830 return Error(E);
6831
6832 // FIXME: What if the initializer_list type has base classes, etc?
6833 Result = APValue(APValue::UninitStruct(), 0, 2);
6834 Array.moveInto(Result.getStructField(0));
6835
6836 if (++Field == Record->field_end())
6837 return Error(E);
6838
6839 if (Field->getType()->isPointerType() &&
6840 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6841 ArrayType->getElementType())) {
6842 // End pointer.
6843 if (!HandleLValueArrayAdjustment(Info, E, Array,
6844 ArrayType->getElementType(),
6845 ArrayType->getSize().getZExtValue()))
6846 return false;
6847 Array.moveInto(Result.getStructField(1));
6848 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6849 // Length.
6850 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6851 else
6852 return Error(E);
6853
6854 if (++Field != Record->field_end())
6855 return Error(E);
6856
6857 return true;
6858}
6859
Faisal Valic72a08c2017-01-09 03:02:53 +00006860bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6861 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6862 if (ClosureClass->isInvalidDecl()) return false;
6863
6864 if (Info.checkingPotentialConstantExpression()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00006865
Faisal Vali051e3a22017-02-16 04:12:21 +00006866 const size_t NumFields =
6867 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006868
6869 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6870 E->capture_init_end()) &&
6871 "The number of lambda capture initializers should equal the number of "
6872 "fields within the closure type");
6873
Faisal Vali051e3a22017-02-16 04:12:21 +00006874 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6875 // Iterate through all the lambda's closure object's fields and initialize
6876 // them.
6877 auto *CaptureInitIt = E->capture_init_begin();
6878 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6879 bool Success = true;
6880 for (const auto *Field : ClosureClass->fields()) {
6881 assert(CaptureInitIt != E->capture_init_end());
6882 // Get the initializer for this field
6883 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00006884
Faisal Vali051e3a22017-02-16 04:12:21 +00006885 // If there is no initializer, either this is a VLA or an error has
6886 // occurred.
6887 if (!CurFieldInit)
6888 return Error(E);
6889
6890 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6891 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6892 if (!Info.keepEvaluatingAfterFailure())
6893 return false;
6894 Success = false;
6895 }
6896 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006897 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006898 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006899}
6900
Richard Smithd62306a2011-11-10 06:34:14 +00006901static bool EvaluateRecord(const Expr *E, const LValue &This,
6902 APValue &Result, EvalInfo &Info) {
6903 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006904 "can't evaluate expression as a record rvalue");
6905 return RecordExprEvaluator(Info, This, Result).Visit(E);
6906}
6907
6908//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006909// Temporary Evaluation
6910//
6911// Temporaries are represented in the AST as rvalues, but generally behave like
6912// lvalues. The full-object of which the temporary is a subobject is implicitly
6913// materialized so that a reference can bind to it.
6914//===----------------------------------------------------------------------===//
6915namespace {
6916class TemporaryExprEvaluator
6917 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6918public:
6919 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006920 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006921
6922 /// Visit an expression which constructs the value of this temporary.
6923 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006924 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
6925 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006926 }
6927
6928 bool VisitCastExpr(const CastExpr *E) {
6929 switch (E->getCastKind()) {
6930 default:
6931 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6932
6933 case CK_ConstructorConversion:
6934 return VisitConstructExpr(E->getSubExpr());
6935 }
6936 }
6937 bool VisitInitListExpr(const InitListExpr *E) {
6938 return VisitConstructExpr(E);
6939 }
6940 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6941 return VisitConstructExpr(E);
6942 }
6943 bool VisitCallExpr(const CallExpr *E) {
6944 return VisitConstructExpr(E);
6945 }
Richard Smith513955c2014-12-17 19:24:30 +00006946 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6947 return VisitConstructExpr(E);
6948 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006949 bool VisitLambdaExpr(const LambdaExpr *E) {
6950 return VisitConstructExpr(E);
6951 }
Richard Smith027bf112011-11-17 22:56:20 +00006952};
6953} // end anonymous namespace
6954
6955/// Evaluate an expression of record type as a temporary.
6956static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006957 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006958 return TemporaryExprEvaluator(Info, Result).Visit(E);
6959}
6960
6961//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006962// Vector Evaluation
6963//===----------------------------------------------------------------------===//
6964
6965namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006966 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006967 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006968 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006969 public:
Mike Stump11289f42009-09-09 15:08:12 +00006970
Richard Smith2d406342011-10-22 21:10:00 +00006971 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6972 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006973
Craig Topper9798b932015-09-29 04:30:05 +00006974 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006975 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6976 // FIXME: remove this APValue copy.
6977 Result = APValue(V.data(), V.size());
6978 return true;
6979 }
Richard Smith2e312c82012-03-03 22:46:17 +00006980 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006981 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006982 Result = V;
6983 return true;
6984 }
Richard Smithfddd3842011-12-30 21:15:51 +00006985 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006986
Richard Smith2d406342011-10-22 21:10:00 +00006987 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006988 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006989 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006990 bool VisitInitListExpr(const InitListExpr *E);
6991 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006992 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006993 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006994 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006995 };
6996} // end anonymous namespace
6997
6998static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006999 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00007000 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007001}
7002
George Burgess IV533ff002015-12-11 00:23:35 +00007003bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007004 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00007005 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00007006
Richard Smith161f09a2011-12-06 22:44:34 +00007007 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00007008 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007009
Eli Friedmanc757de22011-03-25 00:43:55 +00007010 switch (E->getCastKind()) {
7011 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00007012 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00007013 if (SETy->isIntegerType()) {
7014 APSInt IntResult;
7015 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00007016 return false;
7017 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00007018 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00007019 APFloat FloatResult(0.0);
7020 if (!EvaluateFloat(SE, FloatResult, Info))
7021 return false;
7022 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00007023 } else {
Richard Smith2d406342011-10-22 21:10:00 +00007024 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007025 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00007026
7027 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00007028 SmallVector<APValue, 4> Elts(NElts, Val);
7029 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00007030 }
Eli Friedman803acb32011-12-22 03:51:45 +00007031 case CK_BitCast: {
7032 // Evaluate the operand into an APInt we can extract from.
7033 llvm::APInt SValInt;
7034 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
7035 return false;
7036 // Extract the elements
7037 QualType EltTy = VTy->getElementType();
7038 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
7039 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7040 SmallVector<APValue, 4> Elts;
7041 if (EltTy->isRealFloatingType()) {
7042 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00007043 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00007044 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00007045 FloatEltSize = 80;
7046 for (unsigned i = 0; i < NElts; i++) {
7047 llvm::APInt Elt;
7048 if (BigEndian)
7049 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
7050 else
7051 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00007052 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00007053 }
7054 } else if (EltTy->isIntegerType()) {
7055 for (unsigned i = 0; i < NElts; i++) {
7056 llvm::APInt Elt;
7057 if (BigEndian)
7058 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
7059 else
7060 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
7061 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
7062 }
7063 } else {
7064 return Error(E);
7065 }
7066 return Success(Elts, E);
7067 }
Eli Friedmanc757de22011-03-25 00:43:55 +00007068 default:
Richard Smith11562c52011-10-28 17:51:58 +00007069 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007070 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007071}
7072
Richard Smith2d406342011-10-22 21:10:00 +00007073bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007074VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007075 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007076 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00007077 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00007078
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007079 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007080 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007081
Eli Friedmanb9c71292012-01-03 23:24:20 +00007082 // The number of initializers can be less than the number of
7083 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00007084 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00007085 // should be initialized with zeroes.
7086 unsigned CountInits = 0, CountElts = 0;
7087 while (CountElts < NumElements) {
7088 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00007089 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00007090 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00007091 APValue v;
7092 if (!EvaluateVector(E->getInit(CountInits), v, Info))
7093 return Error(E);
7094 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00007095 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00007096 Elements.push_back(v.getVectorElt(j));
7097 CountElts += vlen;
7098 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007099 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007100 if (CountInits < NumInits) {
7101 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007102 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007103 } else // trailing integer zero.
7104 sInt = Info.Ctx.MakeIntValue(0, EltTy);
7105 Elements.push_back(APValue(sInt));
7106 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007107 } else {
7108 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007109 if (CountInits < NumInits) {
7110 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007111 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007112 } else // trailing float zero.
7113 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7114 Elements.push_back(APValue(f));
7115 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00007116 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00007117 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007118 }
Richard Smith2d406342011-10-22 21:10:00 +00007119 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007120}
7121
Richard Smith2d406342011-10-22 21:10:00 +00007122bool
Richard Smithfddd3842011-12-30 21:15:51 +00007123VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007124 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00007125 QualType EltTy = VT->getElementType();
7126 APValue ZeroElement;
7127 if (EltTy->isIntegerType())
7128 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7129 else
7130 ZeroElement =
7131 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7132
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007133 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00007134 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007135}
7136
Richard Smith2d406342011-10-22 21:10:00 +00007137bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00007138 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007139 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007140}
7141
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007142//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00007143// Array Evaluation
7144//===----------------------------------------------------------------------===//
7145
7146namespace {
7147 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007148 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007149 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00007150 APValue &Result;
7151 public:
7152
Richard Smithd62306a2011-11-10 06:34:14 +00007153 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7154 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00007155
7156 bool Success(const APValue &V, const Expr *E) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00007157 assert(V.isArray() && "expected array");
Richard Smithf3e9e432011-11-07 09:22:26 +00007158 Result = V;
7159 return true;
7160 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007161
Richard Smithfddd3842011-12-30 21:15:51 +00007162 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007163 const ConstantArrayType *CAT =
7164 Info.Ctx.getAsConstantArrayType(E->getType());
7165 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007166 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007167
7168 Result = APValue(APValue::UninitArray(), 0,
7169 CAT->getSize().getZExtValue());
7170 if (!Result.hasArrayFiller()) return true;
7171
Richard Smithfddd3842011-12-30 21:15:51 +00007172 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00007173 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007174 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00007175 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00007176 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00007177 }
7178
Richard Smith52a980a2015-08-28 02:43:42 +00007179 bool VisitCallExpr(const CallExpr *E) {
7180 return handleCallExpr(E, Result, &This);
7181 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007182 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00007183 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00007184 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00007185 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7186 const LValue &Subobject,
7187 APValue *Value, QualType Type);
Eli Friedman3bf72d72019-02-08 21:18:46 +00007188 bool VisitStringLiteral(const StringLiteral *E) {
7189 expandStringLiteral(Info, E, Result);
7190 return true;
7191 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007192 };
7193} // end anonymous namespace
7194
Richard Smithd62306a2011-11-10 06:34:14 +00007195static bool EvaluateArray(const Expr *E, const LValue &This,
7196 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00007197 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00007198 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007199}
7200
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007201// Return true iff the given array filler may depend on the element index.
7202static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7203 // For now, just whitelist non-class value-initialization and initialization
7204 // lists comprised of them.
7205 if (isa<ImplicitValueInitExpr>(FillerExpr))
7206 return false;
7207 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7208 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7209 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7210 return true;
7211 }
7212 return false;
7213 }
7214 return true;
7215}
7216
Richard Smithf3e9e432011-11-07 09:22:26 +00007217bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7218 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7219 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007220 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007221
Richard Smithca2cfbf2011-12-22 01:07:19 +00007222 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7223 // an appropriately-typed string literal enclosed in braces.
Eli Friedman3bf72d72019-02-08 21:18:46 +00007224 if (E->isStringLiteralInit())
7225 return Visit(E->getInit(0));
Richard Smithca2cfbf2011-12-22 01:07:19 +00007226
Richard Smith253c2a32012-01-27 01:14:48 +00007227 bool Success = true;
7228
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007229 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7230 "zero-initialized array shouldn't have any initialized elts");
7231 APValue Filler;
7232 if (Result.isArray() && Result.hasArrayFiller())
7233 Filler = Result.getArrayFiller();
7234
Richard Smith9543c5e2013-04-22 14:44:29 +00007235 unsigned NumEltsToInit = E->getNumInits();
7236 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007237 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00007238
7239 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007240 // array element.
7241 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00007242 NumEltsToInit = NumElts;
7243
Nicola Zaghen3538b392018-05-15 13:30:56 +00007244 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
7245 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007246
Richard Smith9543c5e2013-04-22 14:44:29 +00007247 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007248
7249 // If the array was previously zero-initialized, preserve the
7250 // zero-initialized values.
7251 if (!Filler.isUninit()) {
7252 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
7253 Result.getArrayInitializedElt(I) = Filler;
7254 if (Result.hasArrayFiller())
7255 Result.getArrayFiller() = Filler;
7256 }
7257
Richard Smithd62306a2011-11-10 06:34:14 +00007258 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007259 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00007260 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
7261 const Expr *Init =
7262 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00007263 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00007264 Info, Subobject, Init) ||
7265 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00007266 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00007267 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00007268 return false;
7269 Success = false;
7270 }
Richard Smithd62306a2011-11-10 06:34:14 +00007271 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007272
Richard Smith9543c5e2013-04-22 14:44:29 +00007273 if (!Result.hasArrayFiller())
7274 return Success;
7275
7276 // If we get here, we have a trivial filler, which we can just evaluate
7277 // once and splat over the rest of the array elements.
7278 assert(FillerExpr && "no array filler for incomplete init list");
7279 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
7280 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00007281}
7282
Richard Smith410306b2016-12-12 02:53:20 +00007283bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
7284 if (E->getCommonExpr() &&
7285 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
7286 Info, E->getCommonExpr()->getSourceExpr()))
7287 return false;
7288
7289 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7290
7291 uint64_t Elements = CAT->getSize().getZExtValue();
7292 Result = APValue(APValue::UninitArray(), Elements, Elements);
7293
7294 LValue Subobject = This;
7295 Subobject.addArray(Info, E, CAT);
7296
7297 bool Success = true;
7298 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7299 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7300 Info, Subobject, E->getSubExpr()) ||
7301 !HandleLValueArrayAdjustment(Info, E, Subobject,
7302 CAT->getElementType(), 1)) {
7303 if (!Info.noteFailure())
7304 return false;
7305 Success = false;
7306 }
7307 }
7308
7309 return Success;
7310}
7311
Richard Smith027bf112011-11-17 22:56:20 +00007312bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00007313 return VisitCXXConstructExpr(E, This, &Result, E->getType());
7314}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007315
Richard Smith9543c5e2013-04-22 14:44:29 +00007316bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7317 const LValue &Subobject,
7318 APValue *Value,
7319 QualType Type) {
7320 bool HadZeroInit = !Value->isUninit();
7321
7322 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7323 unsigned N = CAT->getSize().getZExtValue();
7324
7325 // Preserve the array filler if we had prior zero-initialization.
7326 APValue Filler =
7327 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7328 : APValue();
7329
7330 *Value = APValue(APValue::UninitArray(), N, N);
7331
7332 if (HadZeroInit)
7333 for (unsigned I = 0; I != N; ++I)
7334 Value->getArrayInitializedElt(I) = Filler;
7335
7336 // Initialize the elements.
7337 LValue ArrayElt = Subobject;
7338 ArrayElt.addArray(Info, E, CAT);
7339 for (unsigned I = 0; I != N; ++I)
7340 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7341 CAT->getElementType()) ||
7342 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7343 CAT->getElementType(), 1))
7344 return false;
7345
7346 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007347 }
Richard Smith027bf112011-11-17 22:56:20 +00007348
Richard Smith9543c5e2013-04-22 14:44:29 +00007349 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00007350 return Error(E);
7351
Richard Smithb8348f52016-05-12 22:16:28 +00007352 return RecordExprEvaluator(Info, Subobject, *Value)
7353 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00007354}
7355
Richard Smithf3e9e432011-11-07 09:22:26 +00007356//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007357// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00007358//
7359// As a GNU extension, we support casting pointers to sufficiently-wide integer
7360// types and back in constant folding. Integer values are thus represented
7361// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00007362//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007363
7364namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007365class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007366 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00007367 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007368public:
Richard Smith2e312c82012-03-03 22:46:17 +00007369 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007370 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007371
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007372 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007373 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007374 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007375 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007376 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007377 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007378 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007379 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007380 return true;
7381 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007382 bool Success(const llvm::APSInt &SI, const Expr *E) {
7383 return Success(SI, E, Result);
7384 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007385
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007386 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007387 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007388 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007389 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007390 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007391 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007392 Result.getInt().setIsUnsigned(
7393 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007394 return true;
7395 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007396 bool Success(const llvm::APInt &I, const Expr *E) {
7397 return Success(I, E, Result);
7398 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007399
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007400 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007401 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007402 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007403 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007404 return true;
7405 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007406 bool Success(uint64_t Value, const Expr *E) {
7407 return Success(Value, E, Result);
7408 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007409
Ken Dyckdbc01912011-03-11 02:13:43 +00007410 bool Success(CharUnits Size, const Expr *E) {
7411 return Success(Size.getQuantity(), E);
7412 }
7413
Richard Smith2e312c82012-03-03 22:46:17 +00007414 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007415 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007416 Result = V;
7417 return true;
7418 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007419 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007420 }
Mike Stump11289f42009-09-09 15:08:12 +00007421
Richard Smithfddd3842011-12-30 21:15:51 +00007422 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007423
Peter Collingbournee9200682011-05-13 03:29:01 +00007424 //===--------------------------------------------------------------------===//
7425 // Visitor Methods
7426 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007427
Fangrui Song407659a2018-11-30 23:41:18 +00007428 bool VisitConstantExpr(const ConstantExpr *E);
7429
Chris Lattner7174bf32008-07-12 00:38:25 +00007430 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007431 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007432 }
7433 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007434 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007435 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007436
7437 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7438 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007439 if (CheckReferencedDecl(E, E->getDecl()))
7440 return true;
7441
7442 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007443 }
7444 bool VisitMemberExpr(const MemberExpr *E) {
7445 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007446 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007447 return true;
7448 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007449
7450 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007451 }
7452
Peter Collingbournee9200682011-05-13 03:29:01 +00007453 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007454 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007455 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007456 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007457 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007458
Peter Collingbournee9200682011-05-13 03:29:01 +00007459 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007460 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007461
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007462 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007463 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007464 }
Mike Stump11289f42009-09-09 15:08:12 +00007465
Ted Kremeneke65b0862012-03-06 20:05:56 +00007466 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7467 return Success(E->getValue(), E);
7468 }
Richard Smith410306b2016-12-12 02:53:20 +00007469
7470 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7471 if (Info.ArrayInitIndex == uint64_t(-1)) {
7472 // We were asked to evaluate this subexpression independent of the
7473 // enclosing ArrayInitLoopExpr. We can't do that.
7474 Info.FFDiag(E);
7475 return false;
7476 }
7477 return Success(Info.ArrayInitIndex, E);
7478 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007479
Richard Smith4ce706a2011-10-11 21:43:33 +00007480 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007481 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007482 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007483 }
7484
Douglas Gregor29c42f22012-02-24 07:38:34 +00007485 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7486 return Success(E->getValue(), E);
7487 }
7488
John Wiegley6242b6a2011-04-28 00:16:57 +00007489 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7490 return Success(E->getValue(), E);
7491 }
7492
John Wiegleyf9f65842011-04-25 06:54:41 +00007493 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7494 return Success(E->getValue(), E);
7495 }
7496
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007497 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007498 bool VisitUnaryImag(const UnaryOperator *E);
7499
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007500 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007501 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007502
Eli Friedman4e7a2412009-02-27 04:45:43 +00007503 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007504};
Leonard Chandb01c3a2018-06-20 17:19:40 +00007505
7506class FixedPointExprEvaluator
7507 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
7508 APValue &Result;
7509
7510 public:
7511 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
7512 : ExprEvaluatorBaseTy(info), Result(result) {}
7513
Leonard Chandb01c3a2018-06-20 17:19:40 +00007514 bool Success(const llvm::APInt &I, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00007515 return Success(
7516 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00007517 }
7518
Leonard Chandb01c3a2018-06-20 17:19:40 +00007519 bool Success(uint64_t Value, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00007520 return Success(
7521 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00007522 }
7523
7524 bool Success(const APValue &V, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00007525 return Success(V.getFixedPoint(), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00007526 }
7527
Leonard Chand3f3e162019-01-18 21:04:25 +00007528 bool Success(const APFixedPoint &V, const Expr *E) {
7529 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7530 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7531 "Invalid evaluation result.");
7532 Result = APValue(V);
7533 return true;
7534 }
Leonard Chandb01c3a2018-06-20 17:19:40 +00007535
7536 //===--------------------------------------------------------------------===//
7537 // Visitor Methods
7538 //===--------------------------------------------------------------------===//
7539
7540 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
7541 return Success(E->getValue(), E);
7542 }
7543
Leonard Chand3f3e162019-01-18 21:04:25 +00007544 bool VisitCastExpr(const CastExpr *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00007545 bool VisitUnaryOperator(const UnaryOperator *E);
Leonard Chand3f3e162019-01-18 21:04:25 +00007546 bool VisitBinaryOperator(const BinaryOperator *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00007547};
Chris Lattner05706e882008-07-11 18:11:29 +00007548} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007549
Richard Smith11562c52011-10-28 17:51:58 +00007550/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7551/// produce either the integer value or a pointer.
7552///
7553/// GCC has a heinous extension which folds casts between pointer types and
7554/// pointer-sized integral types. We support this by allowing the evaluation of
7555/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7556/// Some simple arithmetic on such values is supported (they are treated much
7557/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007558static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007559 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007560 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007561 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007562}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007563
Richard Smithf57d8cb2011-12-09 22:58:01 +00007564static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007565 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007566 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007567 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007568 if (!Val.isInt()) {
7569 // FIXME: It would be better to produce the diagnostic for casting
7570 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007571 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007572 return false;
7573 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007574 Result = Val.getInt();
7575 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007576}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007577
Leonard Chand3f3e162019-01-18 21:04:25 +00007578static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
7579 EvalInfo &Info) {
7580 if (E->getType()->isFixedPointType()) {
7581 APValue Val;
7582 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
7583 return false;
7584 if (!Val.isFixedPoint())
7585 return false;
7586
7587 Result = Val.getFixedPoint();
7588 return true;
7589 }
7590 return false;
7591}
7592
7593static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
7594 EvalInfo &Info) {
7595 if (E->getType()->isIntegerType()) {
7596 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
7597 APSInt Val;
7598 if (!EvaluateInteger(E, Val, Info))
7599 return false;
7600 Result = APFixedPoint(Val, FXSema);
7601 return true;
7602 } else if (E->getType()->isFixedPointType()) {
7603 return EvaluateFixedPoint(E, Result, Info);
7604 }
7605 return false;
7606}
7607
Richard Smithf57d8cb2011-12-09 22:58:01 +00007608/// Check whether the given declaration can be directly converted to an integral
7609/// rvalue. If not, no diagnostic is produced; there are other things we can
7610/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007611bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007612 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007613 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007614 // Check for signedness/width mismatches between E type and ECD value.
7615 bool SameSign = (ECD->getInitVal().isSigned()
7616 == E->getType()->isSignedIntegerOrEnumerationType());
7617 bool SameWidth = (ECD->getInitVal().getBitWidth()
7618 == Info.Ctx.getIntWidth(E->getType()));
7619 if (SameSign && SameWidth)
7620 return Success(ECD->getInitVal(), E);
7621 else {
7622 // Get rid of mismatch (otherwise Success assertions will fail)
7623 // by computing a new value matching the type of E.
7624 llvm::APSInt Val = ECD->getInitVal();
7625 if (!SameSign)
7626 Val.setIsSigned(!ECD->getInitVal().isSigned());
7627 if (!SameWidth)
7628 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7629 return Success(Val, E);
7630 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007631 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007632 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007633}
7634
Richard Smith08b682b2018-05-23 21:18:00 +00007635/// Values returned by __builtin_classify_type, chosen to match the values
7636/// produced by GCC's builtin.
7637enum class GCCTypeClass {
7638 None = -1,
7639 Void = 0,
7640 Integer = 1,
7641 // GCC reserves 2 for character types, but instead classifies them as
7642 // integers.
7643 Enum = 3,
7644 Bool = 4,
7645 Pointer = 5,
7646 // GCC reserves 6 for references, but appears to never use it (because
7647 // expressions never have reference type, presumably).
7648 PointerToDataMember = 7,
7649 RealFloat = 8,
7650 Complex = 9,
7651 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
7652 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
7653 // GCC claims to reserve 11 for pointers to member functions, but *actually*
7654 // uses 12 for that purpose, same as for a class or struct. Maybe it
7655 // internally implements a pointer to member as a struct? Who knows.
7656 PointerToMemberFunction = 12, // Not a bug, see above.
7657 ClassOrStruct = 12,
7658 Union = 13,
7659 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
7660 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
7661 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
7662 // literals.
7663};
7664
Chris Lattner86ee2862008-10-06 06:40:35 +00007665/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7666/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00007667static GCCTypeClass
7668EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
7669 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00007670
Richard Smith08b682b2018-05-23 21:18:00 +00007671 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007672 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7673
7674 switch (CanTy->getTypeClass()) {
7675#define TYPE(ID, BASE)
7676#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7677#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7678#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7679#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00007680 case Type::Auto:
7681 case Type::DeducedTemplateSpecialization:
7682 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007683
7684 case Type::Builtin:
7685 switch (BT->getKind()) {
7686#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00007687#define SIGNED_TYPE(ID, SINGLETON_ID) \
7688 case BuiltinType::ID: return GCCTypeClass::Integer;
7689#define FLOATING_TYPE(ID, SINGLETON_ID) \
7690 case BuiltinType::ID: return GCCTypeClass::RealFloat;
7691#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
7692 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007693#include "clang/AST/BuiltinTypes.def"
7694 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00007695 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007696
7697 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00007698 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007699
Richard Smith08b682b2018-05-23 21:18:00 +00007700 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007701 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00007702 case BuiltinType::WChar_U:
7703 case BuiltinType::Char8:
7704 case BuiltinType::Char16:
7705 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007706 case BuiltinType::UShort:
7707 case BuiltinType::UInt:
7708 case BuiltinType::ULong:
7709 case BuiltinType::ULongLong:
7710 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00007711 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007712
Leonard Chanf921d852018-06-04 16:07:52 +00007713 case BuiltinType::UShortAccum:
7714 case BuiltinType::UAccum:
7715 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00007716 case BuiltinType::UShortFract:
7717 case BuiltinType::UFract:
7718 case BuiltinType::ULongFract:
7719 case BuiltinType::SatUShortAccum:
7720 case BuiltinType::SatUAccum:
7721 case BuiltinType::SatULongAccum:
7722 case BuiltinType::SatUShortFract:
7723 case BuiltinType::SatUFract:
7724 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00007725 return GCCTypeClass::None;
7726
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007727 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007728
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007729 case BuiltinType::ObjCId:
7730 case BuiltinType::ObjCClass:
7731 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007732#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7733 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007734#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00007735#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7736 case BuiltinType::Id:
7737#include "clang/Basic/OpenCLExtensionTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007738 case BuiltinType::OCLSampler:
7739 case BuiltinType::OCLEvent:
7740 case BuiltinType::OCLClkEvent:
7741 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007742 case BuiltinType::OCLReserveID:
Richard Smith08b682b2018-05-23 21:18:00 +00007743 return GCCTypeClass::None;
7744
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007745 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00007746 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007747 };
Richard Smith08b682b2018-05-23 21:18:00 +00007748 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007749
7750 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00007751 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007752
7753 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007754 case Type::ConstantArray:
7755 case Type::VariableArray:
7756 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00007757 case Type::FunctionNoProto:
7758 case Type::FunctionProto:
7759 return GCCTypeClass::Pointer;
7760
7761 case Type::MemberPointer:
7762 return CanTy->isMemberDataPointerType()
7763 ? GCCTypeClass::PointerToDataMember
7764 : GCCTypeClass::PointerToMemberFunction;
7765
7766 case Type::Complex:
7767 return GCCTypeClass::Complex;
7768
7769 case Type::Record:
7770 return CanTy->isUnionType() ? GCCTypeClass::Union
7771 : GCCTypeClass::ClassOrStruct;
7772
7773 case Type::Atomic:
7774 // GCC classifies _Atomic T the same as T.
7775 return EvaluateBuiltinClassifyType(
7776 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007777
7778 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007779 case Type::Vector:
7780 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007781 case Type::ObjCObject:
7782 case Type::ObjCInterface:
7783 case Type::ObjCObjectPointer:
7784 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00007785 // GCC classifies vectors as None. We follow its lead and classify all
7786 // other types that don't fit into the regular classification the same way.
7787 return GCCTypeClass::None;
7788
7789 case Type::LValueReference:
7790 case Type::RValueReference:
7791 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007792 }
7793
Richard Smith08b682b2018-05-23 21:18:00 +00007794 llvm_unreachable("unexpected type class");
7795}
7796
7797/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7798/// as GCC.
7799static GCCTypeClass
7800EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
7801 // If no argument was supplied, default to None. This isn't
7802 // ideal, however it is what gcc does.
7803 if (E->getNumArgs() == 0)
7804 return GCCTypeClass::None;
7805
7806 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
7807 // being an ICE, but still folds it to a constant using the type of the first
7808 // argument.
7809 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00007810}
7811
Richard Smith5fab0c92011-12-28 19:48:30 +00007812/// EvaluateBuiltinConstantPForLValue - Determine the result of
Richard Smith31cfb312019-04-27 02:58:17 +00007813/// __builtin_constant_p when applied to the given pointer.
Richard Smith5fab0c92011-12-28 19:48:30 +00007814///
Richard Smith31cfb312019-04-27 02:58:17 +00007815/// A pointer is only "constant" if it is null (or a pointer cast to integer)
7816/// or it points to the first character of a string literal.
7817static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
7818 APValue::LValueBase Base = LV.getLValueBase();
7819 if (Base.isNull()) {
7820 // A null base is acceptable.
7821 return true;
7822 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
7823 if (!isa<StringLiteral>(E))
7824 return false;
7825 return LV.getLValueOffset().isZero();
7826 } else {
7827 // Any other base is not constant enough for GCC.
7828 return false;
7829 }
Richard Smith5fab0c92011-12-28 19:48:30 +00007830}
7831
7832/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7833/// GCC as we can manage.
Richard Smith31cfb312019-04-27 02:58:17 +00007834static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
Richard Smith37be3362019-05-04 04:00:45 +00007835 // This evaluation is not permitted to have side-effects, so evaluate it in
7836 // a speculative evaluation context.
7837 SpeculativeEvaluationRAII SpeculativeEval(Info);
7838
Richard Smith31cfb312019-04-27 02:58:17 +00007839 // Constant-folding is always enabled for the operand of __builtin_constant_p
7840 // (even when the enclosing evaluation context otherwise requires a strict
7841 // language-specific constant expression).
7842 FoldConstant Fold(Info, true);
7843
Richard Smith5fab0c92011-12-28 19:48:30 +00007844 QualType ArgType = Arg->getType();
7845
7846 // __builtin_constant_p always has one operand. The rules which gcc follows
7847 // are not precisely documented, but are as follows:
7848 //
7849 // - If the operand is of integral, floating, complex or enumeration type,
7850 // and can be folded to a known value of that type, it returns 1.
Richard Smith31cfb312019-04-27 02:58:17 +00007851 // - If the operand can be folded to a pointer to the first character
7852 // of a string literal (or such a pointer cast to an integral type)
7853 // or to a null pointer or an integer cast to a pointer, it returns 1.
Richard Smith5fab0c92011-12-28 19:48:30 +00007854 //
7855 // Otherwise, it returns 0.
7856 //
7857 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
Richard Smith31cfb312019-04-27 02:58:17 +00007858 // its support for this did not work prior to GCC 9 and is not yet well
7859 // understood.
7860 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
7861 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
7862 ArgType->isNullPtrType()) {
7863 APValue V;
7864 if (!::EvaluateAsRValue(Info, Arg, V)) {
7865 Fold.keepDiagnostics();
Richard Smith5fab0c92011-12-28 19:48:30 +00007866 return false;
Richard Smith31cfb312019-04-27 02:58:17 +00007867 }
Richard Smith5fab0c92011-12-28 19:48:30 +00007868
Richard Smith31cfb312019-04-27 02:58:17 +00007869 // For a pointer (possibly cast to integer), there are special rules.
Richard Smith0c6124b2015-12-03 01:36:22 +00007870 if (V.getKind() == APValue::LValue)
7871 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith31cfb312019-04-27 02:58:17 +00007872
7873 // Otherwise, any constant value is good enough.
7874 return V.getKind() != APValue::Uninitialized;
Richard Smith5fab0c92011-12-28 19:48:30 +00007875 }
7876
7877 // Anything else isn't considered to be sufficiently constant.
7878 return false;
7879}
7880
John McCall95007602010-05-10 23:27:23 +00007881/// Retrieves the "underlying object type" of the given expression,
7882/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007883static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007884 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7885 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007886 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007887 } else if (const Expr *E = B.get<const Expr*>()) {
7888 if (isa<CompoundLiteralExpr>(E))
7889 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007890 }
7891
7892 return QualType();
7893}
7894
George Burgess IV3a03fab2015-09-04 21:28:13 +00007895/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007896/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007897/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007898/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7899///
7900/// Always returns an RValue with a pointer representation.
7901static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7902 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7903
7904 auto *NoParens = E->IgnoreParens();
7905 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007906 if (Cast == nullptr)
7907 return NoParens;
7908
7909 // We only conservatively allow a few kinds of casts, because this code is
7910 // inherently a simple solution that seeks to support the common case.
7911 auto CastKind = Cast->getCastKind();
7912 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7913 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007914 return NoParens;
7915
7916 auto *SubExpr = Cast->getSubExpr();
7917 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7918 return NoParens;
7919 return ignorePointerCastsAndParens(SubExpr);
7920}
7921
George Burgess IVa51c4072015-10-16 01:49:01 +00007922/// Checks to see if the given LValue's Designator is at the end of the LValue's
7923/// record layout. e.g.
7924/// struct { struct { int a, b; } fst, snd; } obj;
7925/// obj.fst // no
7926/// obj.snd // yes
7927/// obj.fst.a // no
7928/// obj.fst.b // no
7929/// obj.snd.a // no
7930/// obj.snd.b // yes
7931///
7932/// Please note: this function is specialized for how __builtin_object_size
7933/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007934///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007935/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7936/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007937static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7938 assert(!LVal.Designator.Invalid);
7939
George Burgess IV4168d752016-06-27 19:40:41 +00007940 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7941 const RecordDecl *Parent = FD->getParent();
7942 Invalid = Parent->isInvalidDecl();
7943 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007944 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007945 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007946 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7947 };
7948
7949 auto &Base = LVal.getLValueBase();
7950 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7951 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007952 bool Invalid;
7953 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7954 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007955 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007956 for (auto *FD : IFD->chain()) {
7957 bool Invalid;
7958 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7959 return Invalid;
7960 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007961 }
7962 }
7963
George Burgess IVe3763372016-12-22 02:50:20 +00007964 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007965 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007966 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007967 // If we don't know the array bound, conservatively assume we're looking at
7968 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007969 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00007970 if (BaseType->isIncompleteArrayType())
7971 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7972 else
7973 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00007974 }
7975
7976 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7977 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007978 if (BaseType->isArrayType()) {
7979 // Because __builtin_object_size treats arrays as objects, we can ignore
7980 // the index iff this is the last array in the Designator.
7981 if (I + 1 == E)
7982 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007983 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7984 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007985 if (Index + 1 != CAT->getSize())
7986 return false;
7987 BaseType = CAT->getElementType();
7988 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007989 const auto *CT = BaseType->castAs<ComplexType>();
7990 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007991 if (Index != 1)
7992 return false;
7993 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007994 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007995 bool Invalid;
7996 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7997 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007998 BaseType = FD->getType();
7999 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00008000 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00008001 return false;
8002 }
8003 }
8004 return true;
8005}
8006
George Burgess IVe3763372016-12-22 02:50:20 +00008007/// Tests to see if the LValue has a user-specified designator (that isn't
8008/// necessarily valid). Note that this always returns 'true' if the LValue has
8009/// an unsized array as its first designator entry, because there's currently no
8010/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00008011static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00008012 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00008013 return false;
8014
George Burgess IVe3763372016-12-22 02:50:20 +00008015 if (!LVal.Designator.Entries.empty())
8016 return LVal.Designator.isMostDerivedAnUnsizedArray();
8017
George Burgess IVa51c4072015-10-16 01:49:01 +00008018 if (!LVal.InvalidBase)
8019 return true;
8020
George Burgess IVe3763372016-12-22 02:50:20 +00008021 // If `E` is a MemberExpr, then the first part of the designator is hiding in
8022 // the LValueBase.
8023 const auto *E = LVal.Base.dyn_cast<const Expr *>();
8024 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00008025}
8026
George Burgess IVe3763372016-12-22 02:50:20 +00008027/// Attempts to detect a user writing into a piece of memory that's impossible
8028/// to figure out the size of by just using types.
8029static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
8030 const SubobjectDesignator &Designator = LVal.Designator;
8031 // Notes:
8032 // - Users can only write off of the end when we have an invalid base. Invalid
8033 // bases imply we don't know where the memory came from.
8034 // - We used to be a bit more aggressive here; we'd only be conservative if
8035 // the array at the end was flexible, or if it had 0 or 1 elements. This
8036 // broke some common standard library extensions (PR30346), but was
8037 // otherwise seemingly fine. It may be useful to reintroduce this behavior
8038 // with some sort of whitelist. OTOH, it seems that GCC is always
8039 // conservative with the last element in structs (if it's an array), so our
8040 // current behavior is more compatible than a whitelisting approach would
8041 // be.
8042 return LVal.InvalidBase &&
8043 Designator.Entries.size() == Designator.MostDerivedPathLength &&
8044 Designator.MostDerivedIsArrayElement &&
8045 isDesignatorAtObjectEnd(Ctx, LVal);
8046}
8047
8048/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
8049/// Fails if the conversion would cause loss of precision.
8050static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
8051 CharUnits &Result) {
8052 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
8053 if (Int.ugt(CharUnitsMax))
8054 return false;
8055 Result = CharUnits::fromQuantity(Int.getZExtValue());
8056 return true;
8057}
8058
8059/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
8060/// determine how many bytes exist from the beginning of the object to either
8061/// the end of the current subobject, or the end of the object itself, depending
8062/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00008063///
George Burgess IVe3763372016-12-22 02:50:20 +00008064/// If this returns false, the value of Result is undefined.
8065static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
8066 unsigned Type, const LValue &LVal,
8067 CharUnits &EndOffset) {
8068 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008069
George Burgess IV7fb7e362017-01-03 23:35:19 +00008070 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
8071 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
8072 return false;
8073 return HandleSizeof(Info, ExprLoc, Ty, Result);
8074 };
8075
George Burgess IVe3763372016-12-22 02:50:20 +00008076 // We want to evaluate the size of the entire object. This is a valid fallback
8077 // for when Type=1 and the designator is invalid, because we're asked for an
8078 // upper-bound.
8079 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
8080 // Type=3 wants a lower bound, so we can't fall back to this.
8081 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00008082 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00008083
8084 llvm::APInt APEndOffset;
8085 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8086 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8087 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8088
8089 if (LVal.InvalidBase)
8090 return false;
8091
8092 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00008093 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00008094 }
8095
George Burgess IVe3763372016-12-22 02:50:20 +00008096 // We want to evaluate the size of a subobject.
8097 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008098
8099 // The following is a moderately common idiom in C:
8100 //
8101 // struct Foo { int a; char c[1]; };
8102 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
8103 // strcpy(&F->c[0], Bar);
8104 //
George Burgess IVe3763372016-12-22 02:50:20 +00008105 // In order to not break too much legacy code, we need to support it.
8106 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
8107 // If we can resolve this to an alloc_size call, we can hand that back,
8108 // because we know for certain how many bytes there are to write to.
8109 llvm::APInt APEndOffset;
8110 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8111 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8112 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8113
8114 // If we cannot determine the size of the initial allocation, then we can't
8115 // given an accurate upper-bound. However, we are still able to give
8116 // conservative lower-bounds for Type=3.
8117 if (Type == 1)
8118 return false;
8119 }
8120
8121 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00008122 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008123 return false;
8124
George Burgess IVe3763372016-12-22 02:50:20 +00008125 // According to the GCC documentation, we want the size of the subobject
8126 // denoted by the pointer. But that's not quite right -- what we actually
8127 // want is the size of the immediately-enclosing array, if there is one.
8128 int64_t ElemsRemaining;
8129 if (Designator.MostDerivedIsArrayElement &&
8130 Designator.Entries.size() == Designator.MostDerivedPathLength) {
8131 uint64_t ArraySize = Designator.getMostDerivedArraySize();
8132 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
8133 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8134 } else {
8135 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8136 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008137
George Burgess IVe3763372016-12-22 02:50:20 +00008138 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8139 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008140}
8141
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008142/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +00008143/// returns true and stores the result in @p Size.
8144///
8145/// If @p WasError is non-null, this will report whether the failure to evaluate
8146/// is to be treated as an Error in IntExprEvaluator.
8147static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8148 EvalInfo &Info, uint64_t &Size) {
8149 // Determine the denoted object.
8150 LValue LVal;
8151 {
8152 // The operand of __builtin_object_size is never evaluated for side-effects.
8153 // If there are any, but we can determine the pointed-to object anyway, then
8154 // ignore the side-effects.
8155 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +00008156 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +00008157
8158 if (E->isGLValue()) {
8159 // It's possible for us to be given GLValues if we're called via
8160 // Expr::tryEvaluateObjectSize.
8161 APValue RVal;
8162 if (!EvaluateAsRValue(Info, E, RVal))
8163 return false;
8164 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00008165 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8166 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00008167 return false;
8168 }
8169
8170 // If we point to before the start of the object, there are no accessible
8171 // bytes.
8172 if (LVal.getLValueOffset().isNegative()) {
8173 Size = 0;
8174 return true;
8175 }
8176
8177 CharUnits EndOffset;
8178 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8179 return false;
8180
8181 // If we've fallen outside of the end offset, just pretend there's nothing to
8182 // write to/read from.
8183 if (EndOffset <= LVal.getLValueOffset())
8184 Size = 0;
8185 else
8186 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8187 return true;
John McCall95007602010-05-10 23:27:23 +00008188}
8189
Fangrui Song407659a2018-11-30 23:41:18 +00008190bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
8191 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
8192 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
8193}
8194
Peter Collingbournee9200682011-05-13 03:29:01 +00008195bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00008196 if (unsigned BuiltinOp = E->getBuiltinCallee())
8197 return VisitBuiltinCallExpr(E, BuiltinOp);
8198
8199 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8200}
8201
8202bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8203 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00008204 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008205 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00008206 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00008207
Erik Pilkington9c3b5882019-01-30 20:34:53 +00008208 case Builtin::BI__builtin_dynamic_object_size:
Mike Stump722cedf2009-10-26 18:35:08 +00008209 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00008210 // The type was checked when we built the expression.
8211 unsigned Type =
8212 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8213 assert(Type <= 3 && "unexpected type");
8214
George Burgess IVe3763372016-12-22 02:50:20 +00008215 uint64_t Size;
8216 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8217 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00008218
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008219 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00008220 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00008221
Richard Smith01ade172012-05-23 04:13:20 +00008222 // Expression had no side effects, but we couldn't statically determine the
8223 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008224 switch (Info.EvalMode) {
8225 case EvalInfo::EM_ConstantExpression:
8226 case EvalInfo::EM_PotentialConstantExpression:
8227 case EvalInfo::EM_ConstantFold:
8228 case EvalInfo::EM_EvaluateForOverflow:
8229 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008230 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008231 return Error(E);
8232 case EvalInfo::EM_ConstantExpressionUnevaluated:
8233 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008234 // Reduce it to a constant now.
8235 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008236 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00008237
8238 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00008239 }
8240
Tim Northover314fbfa2018-11-02 13:14:11 +00008241 case Builtin::BI__builtin_os_log_format_buffer_size: {
8242 analyze_os_log::OSLogBufferLayout Layout;
8243 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
8244 return Success(Layout.size().getQuantity(), E);
8245 }
8246
Benjamin Kramera801f4a2012-10-06 14:42:22 +00008247 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00008248 case Builtin::BI__builtin_bswap32:
8249 case Builtin::BI__builtin_bswap64: {
8250 APSInt Val;
8251 if (!EvaluateInteger(E->getArg(0), Val, Info))
8252 return false;
8253
8254 return Success(Val.byteSwap(), E);
8255 }
8256
Richard Smith8889a3d2013-06-13 06:26:32 +00008257 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +00008258 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00008259
Craig Topperf95a6d92018-08-08 22:31:12 +00008260 case Builtin::BI__builtin_clrsb:
8261 case Builtin::BI__builtin_clrsbl:
8262 case Builtin::BI__builtin_clrsbll: {
8263 APSInt Val;
8264 if (!EvaluateInteger(E->getArg(0), Val, Info))
8265 return false;
8266
8267 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
8268 }
Richard Smith8889a3d2013-06-13 06:26:32 +00008269
Richard Smith80b3c8e2013-06-13 05:04:16 +00008270 case Builtin::BI__builtin_clz:
8271 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008272 case Builtin::BI__builtin_clzll:
8273 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008274 APSInt Val;
8275 if (!EvaluateInteger(E->getArg(0), Val, Info))
8276 return false;
8277 if (!Val)
8278 return Error(E);
8279
8280 return Success(Val.countLeadingZeros(), E);
8281 }
8282
Fangrui Song407659a2018-11-30 23:41:18 +00008283 case Builtin::BI__builtin_constant_p: {
Richard Smith31cfb312019-04-27 02:58:17 +00008284 const Expr *Arg = E->getArg(0);
David Blaikie639b3d12019-05-03 18:11:31 +00008285 if (EvaluateBuiltinConstantP(Info, Arg))
Fangrui Song407659a2018-11-30 23:41:18 +00008286 return Success(true, E);
David Blaikie639b3d12019-05-03 18:11:31 +00008287 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
Richard Smithf7d30482019-05-02 23:21:28 +00008288 // Outside a constant context, eagerly evaluate to false in the presence
8289 // of side-effects in order to avoid -Wunsequenced false-positives in
8290 // a branch on __builtin_constant_p(expr).
Richard Smith31cfb312019-04-27 02:58:17 +00008291 return Success(false, E);
Fangrui Song407659a2018-11-30 23:41:18 +00008292 }
David Blaikie639b3d12019-05-03 18:11:31 +00008293 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8294 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00008295 }
Richard Smith8889a3d2013-06-13 06:26:32 +00008296
Eric Fiselieradd16a82019-04-24 02:23:30 +00008297 case Builtin::BI__builtin_is_constant_evaluated:
8298 return Success(Info.InConstantContext, E);
8299
Richard Smith80b3c8e2013-06-13 05:04:16 +00008300 case Builtin::BI__builtin_ctz:
8301 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008302 case Builtin::BI__builtin_ctzll:
8303 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008304 APSInt Val;
8305 if (!EvaluateInteger(E->getArg(0), Val, Info))
8306 return false;
8307 if (!Val)
8308 return Error(E);
8309
8310 return Success(Val.countTrailingZeros(), E);
8311 }
8312
Richard Smith8889a3d2013-06-13 06:26:32 +00008313 case Builtin::BI__builtin_eh_return_data_regno: {
8314 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8315 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
8316 return Success(Operand, E);
8317 }
8318
8319 case Builtin::BI__builtin_expect:
8320 return Visit(E->getArg(0));
8321
8322 case Builtin::BI__builtin_ffs:
8323 case Builtin::BI__builtin_ffsl:
8324 case Builtin::BI__builtin_ffsll: {
8325 APSInt Val;
8326 if (!EvaluateInteger(E->getArg(0), Val, Info))
8327 return false;
8328
8329 unsigned N = Val.countTrailingZeros();
8330 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
8331 }
8332
8333 case Builtin::BI__builtin_fpclassify: {
8334 APFloat Val(0.0);
8335 if (!EvaluateFloat(E->getArg(5), Val, Info))
8336 return false;
8337 unsigned Arg;
8338 switch (Val.getCategory()) {
8339 case APFloat::fcNaN: Arg = 0; break;
8340 case APFloat::fcInfinity: Arg = 1; break;
8341 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
8342 case APFloat::fcZero: Arg = 4; break;
8343 }
8344 return Visit(E->getArg(Arg));
8345 }
8346
8347 case Builtin::BI__builtin_isinf_sign: {
8348 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00008349 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00008350 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
8351 }
8352
Richard Smithea3019d2013-10-15 19:07:14 +00008353 case Builtin::BI__builtin_isinf: {
8354 APFloat Val(0.0);
8355 return EvaluateFloat(E->getArg(0), Val, Info) &&
8356 Success(Val.isInfinity() ? 1 : 0, E);
8357 }
8358
8359 case Builtin::BI__builtin_isfinite: {
8360 APFloat Val(0.0);
8361 return EvaluateFloat(E->getArg(0), Val, Info) &&
8362 Success(Val.isFinite() ? 1 : 0, E);
8363 }
8364
8365 case Builtin::BI__builtin_isnan: {
8366 APFloat Val(0.0);
8367 return EvaluateFloat(E->getArg(0), Val, Info) &&
8368 Success(Val.isNaN() ? 1 : 0, E);
8369 }
8370
8371 case Builtin::BI__builtin_isnormal: {
8372 APFloat Val(0.0);
8373 return EvaluateFloat(E->getArg(0), Val, Info) &&
8374 Success(Val.isNormal() ? 1 : 0, E);
8375 }
8376
Richard Smith8889a3d2013-06-13 06:26:32 +00008377 case Builtin::BI__builtin_parity:
8378 case Builtin::BI__builtin_parityl:
8379 case Builtin::BI__builtin_parityll: {
8380 APSInt Val;
8381 if (!EvaluateInteger(E->getArg(0), Val, Info))
8382 return false;
8383
8384 return Success(Val.countPopulation() % 2, E);
8385 }
8386
Richard Smith80b3c8e2013-06-13 05:04:16 +00008387 case Builtin::BI__builtin_popcount:
8388 case Builtin::BI__builtin_popcountl:
8389 case Builtin::BI__builtin_popcountll: {
8390 APSInt Val;
8391 if (!EvaluateInteger(E->getArg(0), Val, Info))
8392 return false;
8393
8394 return Success(Val.countPopulation(), E);
8395 }
8396
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008397 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00008398 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00008399 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008400 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008401 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00008402 << /*isConstexpr*/0 << /*isConstructor*/0
8403 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00008404 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00008405 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008406 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00008407 case Builtin::BI__builtin_strlen:
8408 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00008409 // As an extension, we support __builtin_strlen() as a constant expression,
8410 // and support folding strlen() to a constant.
8411 LValue String;
8412 if (!EvaluatePointer(E->getArg(0), String, Info))
8413 return false;
8414
Richard Smith8110c9d2016-11-29 19:45:17 +00008415 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8416
Richard Smithe6c19f22013-11-15 02:10:04 +00008417 // Fast path: if it's a string literal, search the string value.
8418 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
8419 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008420 // The string literal may have embedded null characters. Find the first
8421 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00008422 StringRef Str = S->getBytes();
8423 int64_t Off = String.Offset.getQuantity();
8424 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008425 S->getCharByteWidth() == 1 &&
8426 // FIXME: Add fast-path for wchar_t too.
8427 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00008428 Str = Str.substr(Off);
8429
8430 StringRef::size_type Pos = Str.find(0);
8431 if (Pos != StringRef::npos)
8432 Str = Str.substr(0, Pos);
8433
8434 return Success(Str.size(), E);
8435 }
8436
8437 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008438 }
Richard Smithe6c19f22013-11-15 02:10:04 +00008439
8440 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00008441 for (uint64_t Strlen = 0; /**/; ++Strlen) {
8442 APValue Char;
8443 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
8444 !Char.isInt())
8445 return false;
8446 if (!Char.getInt())
8447 return Success(Strlen, E);
8448 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
8449 return false;
8450 }
8451 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008452
Richard Smithe151bab2016-11-11 23:43:35 +00008453 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008454 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008455 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008456 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008457 case Builtin::BImemcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00008458 case Builtin::BIbcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008459 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008460 // A call to strlen is not a constant expression.
8461 if (Info.getLangOpts().CPlusPlus11)
8462 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8463 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00008464 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00008465 else
8466 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008467 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00008468 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008469 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008470 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008471 case Builtin::BI__builtin_wcsncmp:
8472 case Builtin::BI__builtin_memcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00008473 case Builtin::BI__builtin_bcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008474 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00008475 LValue String1, String2;
8476 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
8477 !EvaluatePointer(E->getArg(1), String2, Info))
8478 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00008479
Richard Smithe151bab2016-11-11 23:43:35 +00008480 uint64_t MaxLength = uint64_t(-1);
8481 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008482 BuiltinOp != Builtin::BIwcscmp &&
8483 BuiltinOp != Builtin::BI__builtin_strcmp &&
8484 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00008485 APSInt N;
8486 if (!EvaluateInteger(E->getArg(2), N, Info))
8487 return false;
8488 MaxLength = N.getExtValue();
8489 }
Hubert Tong147b7432018-12-12 16:53:43 +00008490
8491 // Empty substrings compare equal by definition.
8492 if (MaxLength == 0u)
8493 return Success(0, E);
8494
8495 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8496 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8497 String1.Designator.Invalid || String2.Designator.Invalid)
8498 return false;
8499
8500 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
8501 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
8502
8503 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
Clement Courbet8c3343d2019-02-14 12:00:34 +00008504 BuiltinOp == Builtin::BIbcmp ||
8505 BuiltinOp == Builtin::BI__builtin_memcmp ||
8506 BuiltinOp == Builtin::BI__builtin_bcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00008507
8508 assert(IsRawByte ||
8509 (Info.Ctx.hasSameUnqualifiedType(
8510 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
8511 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
8512
8513 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
8514 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
8515 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
8516 Char1.isInt() && Char2.isInt();
8517 };
8518 const auto &AdvanceElems = [&] {
8519 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
8520 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
8521 };
8522
8523 if (IsRawByte) {
8524 uint64_t BytesRemaining = MaxLength;
8525 // Pointers to const void may point to objects of incomplete type.
8526 if (CharTy1->isIncompleteType()) {
8527 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
8528 return false;
8529 }
8530 if (CharTy2->isIncompleteType()) {
8531 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
8532 return false;
8533 }
8534 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
8535 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
8536 // Give up on comparing between elements with disparate widths.
8537 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
8538 return false;
8539 uint64_t BytesPerElement = CharTy1Size.getQuantity();
8540 assert(BytesRemaining && "BytesRemaining should not be zero: the "
8541 "following loop considers at least one element");
8542 while (true) {
8543 APValue Char1, Char2;
8544 if (!ReadCurElems(Char1, Char2))
8545 return false;
8546 // We have compatible in-memory widths, but a possible type and
8547 // (for `bool`) internal representation mismatch.
8548 // Assuming two's complement representation, including 0 for `false` and
8549 // 1 for `true`, we can check an appropriate number of elements for
8550 // equality even if they are not byte-sized.
8551 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
8552 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
8553 if (Char1InMem.ne(Char2InMem)) {
8554 // If the elements are byte-sized, then we can produce a three-way
8555 // comparison result in a straightforward manner.
8556 if (BytesPerElement == 1u) {
8557 // memcmp always compares unsigned chars.
8558 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
8559 }
8560 // The result is byte-order sensitive, and we have multibyte elements.
8561 // FIXME: We can compare the remaining bytes in the correct order.
8562 return false;
8563 }
8564 if (!AdvanceElems())
8565 return false;
8566 if (BytesRemaining <= BytesPerElement)
8567 break;
8568 BytesRemaining -= BytesPerElement;
8569 }
8570 // Enough elements are equal to account for the memcmp limit.
8571 return Success(0, E);
8572 }
8573
Clement Courbet8c3343d2019-02-14 12:00:34 +00008574 bool StopAtNull =
8575 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
8576 BuiltinOp != Builtin::BIwmemcmp &&
8577 BuiltinOp != Builtin::BI__builtin_memcmp &&
8578 BuiltinOp != Builtin::BI__builtin_bcmp &&
8579 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00008580 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
8581 BuiltinOp == Builtin::BIwcsncmp ||
8582 BuiltinOp == Builtin::BIwmemcmp ||
8583 BuiltinOp == Builtin::BI__builtin_wcscmp ||
8584 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
8585 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00008586
Richard Smithe151bab2016-11-11 23:43:35 +00008587 for (; MaxLength; --MaxLength) {
8588 APValue Char1, Char2;
Hubert Tong147b7432018-12-12 16:53:43 +00008589 if (!ReadCurElems(Char1, Char2))
Richard Smithe151bab2016-11-11 23:43:35 +00008590 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00008591 if (Char1.getInt() != Char2.getInt()) {
8592 if (IsWide) // wmemcmp compares with wchar_t signedness.
8593 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
8594 // memcmp always compares unsigned chars.
8595 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
8596 }
Richard Smithe151bab2016-11-11 23:43:35 +00008597 if (StopAtNull && !Char1.getInt())
8598 return Success(0, E);
8599 assert(!(StopAtNull && !Char2.getInt()));
Hubert Tong147b7432018-12-12 16:53:43 +00008600 if (!AdvanceElems())
Richard Smithe151bab2016-11-11 23:43:35 +00008601 return false;
8602 }
8603 // We hit the strncmp / memcmp limit.
8604 return Success(0, E);
8605 }
8606
Richard Smith01ba47d2012-04-13 00:45:38 +00008607 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00008608 case Builtin::BI__atomic_is_lock_free:
8609 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00008610 APSInt SizeVal;
8611 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8612 return false;
8613
8614 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8615 // of two less than the maximum inline atomic width, we know it is
8616 // lock-free. If the size isn't a power of two, or greater than the
8617 // maximum alignment where we promote atomics, we know it is not lock-free
8618 // (at least not in the sense of atomic_is_lock_free). Otherwise,
8619 // the answer can only be determined at runtime; for example, 16-byte
8620 // atomics have lock-free implementations on some, but not all,
8621 // x86-64 processors.
8622
8623 // Check power-of-two.
8624 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00008625 if (Size.isPowerOfTwo()) {
8626 // Check against inlining width.
8627 unsigned InlineWidthBits =
8628 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8629 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8630 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8631 Size == CharUnits::One() ||
8632 E->getArg(1)->isNullPointerConstant(Info.Ctx,
8633 Expr::NPC_NeverValueDependent))
8634 // OK, we will inline appropriately-aligned operations of this size,
8635 // and _Atomic(T) is appropriately-aligned.
8636 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008637
Richard Smith01ba47d2012-04-13 00:45:38 +00008638 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8639 castAs<PointerType>()->getPointeeType();
8640 if (!PointeeType->isIncompleteType() &&
8641 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8642 // OK, we will inline operations on this object.
8643 return Success(1, E);
8644 }
8645 }
8646 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008647
Richard Smith01ba47d2012-04-13 00:45:38 +00008648 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8649 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008650 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00008651 case Builtin::BIomp_is_initial_device:
8652 // We can decide statically which value the runtime would return if called.
8653 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +00008654 case Builtin::BI__builtin_add_overflow:
8655 case Builtin::BI__builtin_sub_overflow:
8656 case Builtin::BI__builtin_mul_overflow:
8657 case Builtin::BI__builtin_sadd_overflow:
8658 case Builtin::BI__builtin_uadd_overflow:
8659 case Builtin::BI__builtin_uaddl_overflow:
8660 case Builtin::BI__builtin_uaddll_overflow:
8661 case Builtin::BI__builtin_usub_overflow:
8662 case Builtin::BI__builtin_usubl_overflow:
8663 case Builtin::BI__builtin_usubll_overflow:
8664 case Builtin::BI__builtin_umul_overflow:
8665 case Builtin::BI__builtin_umull_overflow:
8666 case Builtin::BI__builtin_umulll_overflow:
8667 case Builtin::BI__builtin_saddl_overflow:
8668 case Builtin::BI__builtin_saddll_overflow:
8669 case Builtin::BI__builtin_ssub_overflow:
8670 case Builtin::BI__builtin_ssubl_overflow:
8671 case Builtin::BI__builtin_ssubll_overflow:
8672 case Builtin::BI__builtin_smul_overflow:
8673 case Builtin::BI__builtin_smull_overflow:
8674 case Builtin::BI__builtin_smulll_overflow: {
8675 LValue ResultLValue;
8676 APSInt LHS, RHS;
8677
8678 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
8679 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
8680 !EvaluateInteger(E->getArg(1), RHS, Info) ||
8681 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
8682 return false;
8683
8684 APSInt Result;
8685 bool DidOverflow = false;
8686
8687 // If the types don't have to match, enlarge all 3 to the largest of them.
8688 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8689 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8690 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8691 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
8692 ResultType->isSignedIntegerOrEnumerationType();
8693 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
8694 ResultType->isSignedIntegerOrEnumerationType();
8695 uint64_t LHSSize = LHS.getBitWidth();
8696 uint64_t RHSSize = RHS.getBitWidth();
8697 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
8698 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
8699
8700 // Add an additional bit if the signedness isn't uniformly agreed to. We
8701 // could do this ONLY if there is a signed and an unsigned that both have
8702 // MaxBits, but the code to check that is pretty nasty. The issue will be
8703 // caught in the shrink-to-result later anyway.
8704 if (IsSigned && !AllSigned)
8705 ++MaxBits;
8706
8707 LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
8708 !IsSigned);
8709 RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
8710 !IsSigned);
8711 Result = APSInt(MaxBits, !IsSigned);
8712 }
8713
8714 // Find largest int.
8715 switch (BuiltinOp) {
8716 default:
8717 llvm_unreachable("Invalid value for BuiltinOp");
8718 case Builtin::BI__builtin_add_overflow:
8719 case Builtin::BI__builtin_sadd_overflow:
8720 case Builtin::BI__builtin_saddl_overflow:
8721 case Builtin::BI__builtin_saddll_overflow:
8722 case Builtin::BI__builtin_uadd_overflow:
8723 case Builtin::BI__builtin_uaddl_overflow:
8724 case Builtin::BI__builtin_uaddll_overflow:
8725 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
8726 : LHS.uadd_ov(RHS, DidOverflow);
8727 break;
8728 case Builtin::BI__builtin_sub_overflow:
8729 case Builtin::BI__builtin_ssub_overflow:
8730 case Builtin::BI__builtin_ssubl_overflow:
8731 case Builtin::BI__builtin_ssubll_overflow:
8732 case Builtin::BI__builtin_usub_overflow:
8733 case Builtin::BI__builtin_usubl_overflow:
8734 case Builtin::BI__builtin_usubll_overflow:
8735 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
8736 : LHS.usub_ov(RHS, DidOverflow);
8737 break;
8738 case Builtin::BI__builtin_mul_overflow:
8739 case Builtin::BI__builtin_smul_overflow:
8740 case Builtin::BI__builtin_smull_overflow:
8741 case Builtin::BI__builtin_smulll_overflow:
8742 case Builtin::BI__builtin_umul_overflow:
8743 case Builtin::BI__builtin_umull_overflow:
8744 case Builtin::BI__builtin_umulll_overflow:
8745 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
8746 : LHS.umul_ov(RHS, DidOverflow);
8747 break;
8748 }
8749
8750 // In the case where multiple sizes are allowed, truncate and see if
8751 // the values are the same.
8752 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8753 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8754 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8755 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
8756 // since it will give us the behavior of a TruncOrSelf in the case where
8757 // its parameter <= its size. We previously set Result to be at least the
8758 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
8759 // will work exactly like TruncOrSelf.
8760 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
8761 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
8762
8763 if (!APSInt::isSameValue(Temp, Result))
8764 DidOverflow = true;
8765 Result = Temp;
8766 }
8767
8768 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +00008769 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
8770 return false;
Erich Keane00958272018-06-13 20:43:27 +00008771 return Success(DidOverflow, E);
8772 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008773 }
Chris Lattner7174bf32008-07-12 00:38:25 +00008774}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008775
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008776/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +00008777/// object referred to by the lvalue.
8778static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8779 const LValue &LV) {
8780 // A null pointer can be viewed as being "past the end" but we don't
8781 // choose to look at it that way here.
8782 if (!LV.getLValueBase())
8783 return false;
8784
8785 // If the designator is valid and refers to a subobject, we're not pointing
8786 // past the end.
8787 if (!LV.getLValueDesignator().Invalid &&
8788 !LV.getLValueDesignator().isOnePastTheEnd())
8789 return false;
8790
David Majnemerc378ca52015-08-29 08:32:55 +00008791 // A pointer to an incomplete type might be past-the-end if the type's size is
8792 // zero. We cannot tell because the type is incomplete.
8793 QualType Ty = getType(LV.getLValueBase());
8794 if (Ty->isIncompleteType())
8795 return true;
8796
Richard Smithd20f1e62014-10-21 23:01:04 +00008797 // We're a past-the-end pointer if we point to the byte after the object,
8798 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008799 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008800 return LV.getLValueOffset() == Size;
8801}
8802
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008803namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008804
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008805/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008806///
8807/// We use a data recursive algorithm for binary operators so that we are able
8808/// to handle extreme cases of chained binary operators without causing stack
8809/// overflow.
8810class DataRecursiveIntBinOpEvaluator {
8811 struct EvalResult {
8812 APValue Val;
8813 bool Failed;
8814
8815 EvalResult() : Failed(false) { }
8816
8817 void swap(EvalResult &RHS) {
8818 Val.swap(RHS.Val);
8819 Failed = RHS.Failed;
8820 RHS.Failed = false;
8821 }
8822 };
8823
8824 struct Job {
8825 const Expr *E;
8826 EvalResult LHSResult; // meaningful only for binary operator expression.
8827 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008828
David Blaikie73726062015-08-12 23:09:24 +00008829 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008830 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008831
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008832 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008833 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008834 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008835
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008836 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008837 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008838 };
8839
8840 SmallVector<Job, 16> Queue;
8841
8842 IntExprEvaluator &IntEval;
8843 EvalInfo &Info;
8844 APValue &FinalResult;
8845
8846public:
8847 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8848 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8849
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008850 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008851 /// data recursively.
8852 /// We handle binary operators that are comma, logical, or that have operands
8853 /// with integral or enumeration type.
8854 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008855 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
8856 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +00008857 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008858 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008859 }
8860
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008861 bool Traverse(const BinaryOperator *E) {
8862 enqueue(E);
8863 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008864 while (!Queue.empty())
8865 process(PrevResult);
8866
8867 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008868
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008869 FinalResult.swap(PrevResult.Val);
8870 return true;
8871 }
8872
8873private:
8874 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8875 return IntEval.Success(Value, E, Result);
8876 }
8877 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8878 return IntEval.Success(Value, E, Result);
8879 }
8880 bool Error(const Expr *E) {
8881 return IntEval.Error(E);
8882 }
8883 bool Error(const Expr *E, diag::kind D) {
8884 return IntEval.Error(E, D);
8885 }
8886
8887 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8888 return Info.CCEDiag(E, D);
8889 }
8890
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008891 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008892 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008893 bool &SuppressRHSDiags);
8894
8895 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8896 const BinaryOperator *E, APValue &Result);
8897
8898 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8899 Result.Failed = !Evaluate(Result.Val, Info, E);
8900 if (Result.Failed)
8901 Result.Val = APValue();
8902 }
8903
Richard Trieuba4d0872012-03-21 23:30:30 +00008904 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008905
8906 void enqueue(const Expr *E) {
8907 E = E->IgnoreParens();
8908 Queue.resize(Queue.size()+1);
8909 Queue.back().E = E;
8910 Queue.back().Kind = Job::AnyExprKind;
8911 }
8912};
8913
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008914}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008915
8916bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008917 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008918 bool &SuppressRHSDiags) {
8919 if (E->getOpcode() == BO_Comma) {
8920 // Ignore LHS but note if we could not evaluate it.
8921 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008922 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008923 return true;
8924 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008925
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008926 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008927 bool LHSAsBool;
8928 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008929 // We were able to evaluate the LHS, see if we can get away with not
8930 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008931 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8932 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008933 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008934 }
8935 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008936 LHSResult.Failed = true;
8937
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008938 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008939 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008940 if (!Info.noteSideEffect())
8941 return false;
8942
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008943 // We can't evaluate the LHS; however, sometimes the result
8944 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8945 // Don't ignore RHS and suppress diagnostics from this arm.
8946 SuppressRHSDiags = true;
8947 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008948
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008949 return true;
8950 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008951
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008952 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8953 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008954
George Burgess IVa145e252016-05-25 22:38:36 +00008955 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008956 return false; // Ignore RHS;
8957
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008958 return true;
8959}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008960
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008961static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8962 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008963 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8964 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8965 // offsets.
8966 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8967 CharUnits &Offset = LVal.getLValueOffset();
8968 uint64_t Offset64 = Offset.getQuantity();
8969 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8970 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8971 : Offset64 + Index64);
8972}
8973
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008974bool DataRecursiveIntBinOpEvaluator::
8975 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8976 const BinaryOperator *E, APValue &Result) {
8977 if (E->getOpcode() == BO_Comma) {
8978 if (RHSResult.Failed)
8979 return false;
8980 Result = RHSResult.Val;
8981 return true;
8982 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008983
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008984 if (E->isLogicalOp()) {
8985 bool lhsResult, rhsResult;
8986 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8987 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +00008988
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008989 if (LHSIsOK) {
8990 if (RHSIsOK) {
8991 if (E->getOpcode() == BO_LOr)
8992 return Success(lhsResult || rhsResult, E, Result);
8993 else
8994 return Success(lhsResult && rhsResult, E, Result);
8995 }
8996 } else {
8997 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008998 // We can't evaluate the LHS; however, sometimes the result
8999 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
9000 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009001 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009002 }
9003 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009004
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009005 return false;
9006 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009007
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009008 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9009 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +00009010
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009011 if (LHSResult.Failed || RHSResult.Failed)
9012 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009013
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009014 const APValue &LHSVal = LHSResult.Val;
9015 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +00009016
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009017 // Handle cases like (unsigned long)&a + 4.
9018 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
9019 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00009020 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009021 return true;
9022 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009023
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009024 // Handle cases like 4 + (unsigned long)&a
9025 if (E->getOpcode() == BO_Add &&
9026 RHSVal.isLValue() && LHSVal.isInt()) {
9027 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00009028 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009029 return true;
9030 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009031
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009032 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
9033 // Handle (intptr_t)&&A - (intptr_t)&&B.
9034 if (!LHSVal.getLValueOffset().isZero() ||
9035 !RHSVal.getLValueOffset().isZero())
9036 return false;
9037 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
9038 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
9039 if (!LHSExpr || !RHSExpr)
9040 return false;
9041 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9042 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9043 if (!LHSAddrExpr || !RHSAddrExpr)
9044 return false;
9045 // Make sure both labels come from the same function.
9046 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9047 RHSAddrExpr->getLabel()->getDeclContext())
9048 return false;
9049 Result = APValue(LHSAddrExpr, RHSAddrExpr);
9050 return true;
9051 }
Richard Smith43e77732013-05-07 04:50:00 +00009052
9053 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009054 if (!LHSVal.isInt() || !RHSVal.isInt())
9055 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00009056
9057 // Set up the width and signedness manually, in case it can't be deduced
9058 // from the operation we're performing.
9059 // FIXME: Don't do this in the cases where we can deduce it.
9060 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
9061 E->getType()->isUnsignedIntegerOrEnumerationType());
9062 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
9063 RHSVal.getInt(), Value))
9064 return false;
9065 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009066}
9067
Richard Trieuba4d0872012-03-21 23:30:30 +00009068void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009069 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +00009070
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009071 switch (job.Kind) {
9072 case Job::AnyExprKind: {
9073 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
9074 if (shouldEnqueue(Bop)) {
9075 job.Kind = Job::BinOpKind;
9076 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00009077 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009078 }
9079 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009080
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009081 EvaluateExpr(job.E, Result);
9082 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009083 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009084 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009085
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009086 case Job::BinOpKind: {
9087 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009088 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009089 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009090 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009091 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009092 }
9093 if (SuppressRHSDiags)
9094 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009095 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009096 job.Kind = Job::BinOpVisitedLHSKind;
9097 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00009098 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009099 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009100
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009101 case Job::BinOpVisitedLHSKind: {
9102 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9103 EvalResult RHS;
9104 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00009105 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009106 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009107 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009108 }
9109 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009110
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009111 llvm_unreachable("Invalid Job::Kind!");
9112}
9113
George Burgess IV8c892b52016-05-25 22:31:54 +00009114namespace {
9115/// Used when we determine that we should fail, but can keep evaluating prior to
9116/// noting that we had a failure.
9117class DelayedNoteFailureRAII {
9118 EvalInfo &Info;
9119 bool NoteFailure;
9120
9121public:
9122 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
9123 : Info(Info), NoteFailure(NoteFailure) {}
9124 ~DelayedNoteFailureRAII() {
9125 if (NoteFailure) {
9126 bool ContinueAfterFailure = Info.noteFailure();
9127 (void)ContinueAfterFailure;
9128 assert(ContinueAfterFailure &&
9129 "Shouldn't have kept evaluating on failure.");
9130 }
9131 }
9132};
9133}
9134
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009135template <class SuccessCB, class AfterCB>
9136static bool
9137EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
9138 SuccessCB &&Success, AfterCB &&DoAfter) {
9139 assert(E->isComparisonOp() && "expected comparison operator");
9140 assert((E->getOpcode() == BO_Cmp ||
9141 E->getType()->isIntegralOrEnumerationType()) &&
9142 "unsupported binary expression evaluation");
9143 auto Error = [&](const Expr *E) {
9144 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9145 return false;
9146 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009147
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009148 using CCR = ComparisonCategoryResult;
9149 bool IsRelational = E->isRelationalOp();
9150 bool IsEquality = E->isEqualityOp();
9151 if (E->getOpcode() == BO_Cmp) {
9152 const ComparisonCategoryInfo &CmpInfo =
9153 Info.Ctx.CompCategories.getInfoForType(E->getType());
9154 IsRelational = CmpInfo.isOrdered();
9155 IsEquality = CmpInfo.isEquality();
9156 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00009157
Anders Carlssonacc79812008-11-16 07:17:21 +00009158 QualType LHSTy = E->getLHS()->getType();
9159 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009160
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009161 if (LHSTy->isIntegralOrEnumerationType() &&
9162 RHSTy->isIntegralOrEnumerationType()) {
9163 APSInt LHS, RHS;
9164 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
9165 if (!LHSOK && !Info.noteFailure())
9166 return false;
9167 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
9168 return false;
9169 if (LHS < RHS)
9170 return Success(CCR::Less, E);
9171 if (LHS > RHS)
9172 return Success(CCR::Greater, E);
9173 return Success(CCR::Equal, E);
9174 }
9175
Leonard Chance1d4f12019-02-21 20:50:09 +00009176 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
9177 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
9178 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
9179
9180 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
9181 if (!LHSOK && !Info.noteFailure())
9182 return false;
9183 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
9184 return false;
9185 if (LHSFX < RHSFX)
9186 return Success(CCR::Less, E);
9187 if (LHSFX > RHSFX)
9188 return Success(CCR::Greater, E);
9189 return Success(CCR::Equal, E);
9190 }
9191
Chandler Carruthb29a7432014-10-11 11:03:30 +00009192 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009193 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00009194 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00009195 if (E->isAssignmentOp()) {
9196 LValue LV;
9197 EvaluateLValue(E->getLHS(), LV, Info);
9198 LHSOK = false;
9199 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00009200 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
9201 if (LHSOK) {
9202 LHS.makeComplexFloat();
9203 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
9204 }
9205 } else {
9206 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
9207 }
George Burgess IVa145e252016-05-25 22:38:36 +00009208 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009209 return false;
9210
Chandler Carruthb29a7432014-10-11 11:03:30 +00009211 if (E->getRHS()->getType()->isRealFloatingType()) {
9212 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
9213 return false;
9214 RHS.makeComplexFloat();
9215 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
9216 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009217 return false;
9218
9219 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00009220 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009221 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00009222 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009223 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009224 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
9225 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009226 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009227 assert(IsEquality && "invalid complex comparison");
9228 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
9229 LHS.getComplexIntImag() == RHS.getComplexIntImag();
9230 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009231 }
9232 }
Mike Stump11289f42009-09-09 15:08:12 +00009233
Anders Carlssonacc79812008-11-16 07:17:21 +00009234 if (LHSTy->isRealFloatingType() &&
9235 RHSTy->isRealFloatingType()) {
9236 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00009237
Richard Smith253c2a32012-01-27 01:14:48 +00009238 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009239 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00009240 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009241
Richard Smith253c2a32012-01-27 01:14:48 +00009242 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00009243 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009244
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009245 assert(E->isComparisonOp() && "Invalid binary operator!");
9246 auto GetCmpRes = [&]() {
9247 switch (LHS.compare(RHS)) {
9248 case APFloat::cmpEqual:
9249 return CCR::Equal;
9250 case APFloat::cmpLessThan:
9251 return CCR::Less;
9252 case APFloat::cmpGreaterThan:
9253 return CCR::Greater;
9254 case APFloat::cmpUnordered:
9255 return CCR::Unordered;
9256 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +00009257 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009258 };
9259 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +00009260 }
Mike Stump11289f42009-09-09 15:08:12 +00009261
Eli Friedmana38da572009-04-28 19:17:36 +00009262 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009263 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +00009264
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009265 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9266 if (!LHSOK && !Info.noteFailure())
9267 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009268
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009269 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9270 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009271
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009272 // Reject differing bases from the normal codepath; we special-case
9273 // comparisons to null.
9274 if (!HasSameBase(LHSValue, RHSValue)) {
9275 // Inequalities and subtractions between unrelated pointers have
9276 // unspecified or undefined behavior.
9277 if (!IsEquality)
9278 return Error(E);
9279 // A constant address may compare equal to the address of a symbol.
9280 // The one exception is that address of an object cannot compare equal
9281 // to a null pointer constant.
9282 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
9283 (!RHSValue.Base && !RHSValue.Offset.isZero()))
9284 return Error(E);
9285 // It's implementation-defined whether distinct literals will have
9286 // distinct addresses. In clang, the result of such a comparison is
9287 // unspecified, so it is not a constant expression. However, we do know
9288 // that the address of a literal will be non-null.
9289 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
9290 LHSValue.Base && RHSValue.Base)
9291 return Error(E);
9292 // We can't tell whether weak symbols will end up pointing to the same
9293 // object.
9294 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
9295 return Error(E);
9296 // We can't compare the address of the start of one object with the
9297 // past-the-end address of another object, per C++ DR1652.
9298 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
9299 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
9300 (RHSValue.Base && RHSValue.Offset.isZero() &&
9301 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
9302 return Error(E);
9303 // We can't tell whether an object is at the same address as another
9304 // zero sized object.
9305 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
9306 (LHSValue.Base && isZeroSized(RHSValue)))
9307 return Error(E);
9308 return Success(CCR::Nonequal, E);
9309 }
Eli Friedman64004332009-03-23 04:38:34 +00009310
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009311 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9312 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +00009313
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009314 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9315 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +00009316
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009317 // C++11 [expr.rel]p3:
9318 // Pointers to void (after pointer conversions) can be compared, with a
9319 // result defined as follows: If both pointers represent the same
9320 // address or are both the null pointer value, the result is true if the
9321 // operator is <= or >= and false otherwise; otherwise the result is
9322 // unspecified.
9323 // We interpret this as applying to pointers to *cv* void.
9324 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
9325 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +00009326
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009327 // C++11 [expr.rel]p2:
9328 // - If two pointers point to non-static data members of the same object,
9329 // or to subobjects or array elements fo such members, recursively, the
9330 // pointer to the later declared member compares greater provided the
9331 // two members have the same access control and provided their class is
9332 // not a union.
9333 // [...]
9334 // - Otherwise pointer comparisons are unspecified.
9335 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
9336 bool WasArrayIndex;
9337 unsigned Mismatch = FindDesignatorMismatch(
9338 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
9339 // At the point where the designators diverge, the comparison has a
9340 // specified value if:
9341 // - we are comparing array indices
9342 // - we are comparing fields of a union, or fields with the same access
9343 // Otherwise, the result is unspecified and thus the comparison is not a
9344 // constant expression.
9345 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
9346 Mismatch < RHSDesignator.Entries.size()) {
9347 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
9348 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
9349 if (!LF && !RF)
9350 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
9351 else if (!LF)
9352 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009353 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
9354 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009355 else if (!RF)
9356 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009357 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
9358 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009359 else if (!LF->getParent()->isUnion() &&
9360 LF->getAccess() != RF->getAccess())
9361 Info.CCEDiag(E,
9362 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009363 << LF << LF->getAccess() << RF << RF->getAccess()
9364 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +00009365 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009366 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009367
9368 // The comparison here must be unsigned, and performed with the same
9369 // width as the pointer.
9370 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
9371 uint64_t CompareLHS = LHSOffset.getQuantity();
9372 uint64_t CompareRHS = RHSOffset.getQuantity();
9373 assert(PtrSize <= 64 && "Unexpected pointer width");
9374 uint64_t Mask = ~0ULL >> (64 - PtrSize);
9375 CompareLHS &= Mask;
9376 CompareRHS &= Mask;
9377
9378 // If there is a base and this is a relational operator, we can only
9379 // compare pointers within the object in question; otherwise, the result
9380 // depends on where the object is located in memory.
9381 if (!LHSValue.Base.isNull() && IsRelational) {
9382 QualType BaseTy = getType(LHSValue.Base);
9383 if (BaseTy->isIncompleteType())
9384 return Error(E);
9385 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
9386 uint64_t OffsetLimit = Size.getQuantity();
9387 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
9388 return Error(E);
9389 }
9390
9391 if (CompareLHS < CompareRHS)
9392 return Success(CCR::Less, E);
9393 if (CompareLHS > CompareRHS)
9394 return Success(CCR::Greater, E);
9395 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009396 }
Richard Smith7bb00672012-02-01 01:42:44 +00009397
9398 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009399 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +00009400 assert(RHSTy->isMemberPointerType() && "invalid comparison");
9401
9402 MemberPtr LHSValue, RHSValue;
9403
9404 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009405 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00009406 return false;
9407
9408 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9409 return false;
9410
9411 // C++11 [expr.eq]p2:
9412 // If both operands are null, they compare equal. Otherwise if only one is
9413 // null, they compare unequal.
9414 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
9415 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009416 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009417 }
9418
9419 // Otherwise if either is a pointer to a virtual member function, the
9420 // result is unspecified.
9421 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
9422 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009423 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009424 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
9425 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009426 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009427
9428 // Otherwise they compare equal if and only if they would refer to the
9429 // same member of the same most derived object or the same subobject if
9430 // they were dereferenced with a hypothetical object of the associated
9431 // class type.
9432 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009433 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009434 }
9435
Richard Smithab44d9b2012-02-14 22:35:28 +00009436 if (LHSTy->isNullPtrType()) {
9437 assert(E->isComparisonOp() && "unexpected nullptr operation");
9438 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
9439 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
9440 // are compared, the result is true of the operator is <=, >= or ==, and
9441 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009442 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +00009443 }
9444
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009445 return DoAfter();
9446}
9447
9448bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
9449 if (!CheckLiteralType(Info, E))
9450 return false;
9451
9452 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9453 const BinaryOperator *E) {
9454 // Evaluation succeeded. Lookup the information for the comparison category
9455 // type and fetch the VarDecl for the result.
9456 const ComparisonCategoryInfo &CmpInfo =
9457 Info.Ctx.CompCategories.getInfoForType(E->getType());
9458 const VarDecl *VD =
9459 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
9460 // Check and evaluate the result as a constant expression.
9461 LValue LV;
9462 LV.set(VD);
9463 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9464 return false;
9465 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9466 };
9467 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9468 return ExprEvaluatorBaseTy::VisitBinCmp(E);
9469 });
9470}
9471
9472bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9473 // We don't call noteFailure immediately because the assignment happens after
9474 // we evaluate LHS and RHS.
9475 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
9476 return Error(E);
9477
9478 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
9479 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
9480 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
9481
9482 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
9483 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009484 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009485
9486 if (E->isComparisonOp()) {
9487 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
9488 // comparisons and then translating the result.
9489 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9490 const BinaryOperator *E) {
9491 using CCR = ComparisonCategoryResult;
9492 bool IsEqual = ResKind == CCR::Equal,
9493 IsLess = ResKind == CCR::Less,
9494 IsGreater = ResKind == CCR::Greater;
9495 auto Op = E->getOpcode();
9496 switch (Op) {
9497 default:
9498 llvm_unreachable("unsupported binary operator");
9499 case BO_EQ:
9500 case BO_NE:
9501 return Success(IsEqual == (Op == BO_EQ), E);
9502 case BO_LT: return Success(IsLess, E);
9503 case BO_GT: return Success(IsGreater, E);
9504 case BO_LE: return Success(IsEqual || IsLess, E);
9505 case BO_GE: return Success(IsEqual || IsGreater, E);
9506 }
9507 };
9508 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9509 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9510 });
9511 }
9512
9513 QualType LHSTy = E->getLHS()->getType();
9514 QualType RHSTy = E->getRHS()->getType();
9515
9516 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
9517 E->getOpcode() == BO_Sub) {
9518 LValue LHSValue, RHSValue;
9519
9520 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9521 if (!LHSOK && !Info.noteFailure())
9522 return false;
9523
9524 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9525 return false;
9526
9527 // Reject differing bases from the normal codepath; we special-case
9528 // comparisons to null.
9529 if (!HasSameBase(LHSValue, RHSValue)) {
9530 // Handle &&A - &&B.
9531 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
9532 return Error(E);
9533 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
9534 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
9535 if (!LHSExpr || !RHSExpr)
9536 return Error(E);
9537 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9538 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9539 if (!LHSAddrExpr || !RHSAddrExpr)
9540 return Error(E);
9541 // Make sure both labels come from the same function.
9542 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9543 RHSAddrExpr->getLabel()->getDeclContext())
9544 return Error(E);
9545 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
9546 }
9547 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9548 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9549
9550 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9551 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9552
9553 // C++11 [expr.add]p6:
9554 // Unless both pointers point to elements of the same array object, or
9555 // one past the last element of the array object, the behavior is
9556 // undefined.
9557 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
9558 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
9559 RHSDesignator))
9560 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
9561
9562 QualType Type = E->getLHS()->getType();
9563 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
9564
9565 CharUnits ElementSize;
9566 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
9567 return false;
9568
9569 // As an extension, a type may have zero size (empty struct or union in
9570 // C, array of zero length). Pointer subtraction in such cases has
9571 // undefined behavior, so is not constant.
9572 if (ElementSize.isZero()) {
9573 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
9574 << ElementType;
9575 return false;
9576 }
9577
9578 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
9579 // and produce incorrect results when it overflows. Such behavior
9580 // appears to be non-conforming, but is common, so perhaps we should
9581 // assume the standard intended for such cases to be undefined behavior
9582 // and check for them.
9583
9584 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
9585 // overflow in the final conversion to ptrdiff_t.
9586 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
9587 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
9588 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
9589 false);
9590 APSInt TrueResult = (LHS - RHS) / ElemSize;
9591 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
9592
9593 if (Result.extend(65) != TrueResult &&
9594 !HandleOverflow(Info, E, TrueResult, E->getType()))
9595 return false;
9596 return Success(Result, E);
9597 }
9598
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009599 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00009600}
9601
Peter Collingbournee190dee2011-03-11 19:24:49 +00009602/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
9603/// a result as the expression's type.
9604bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
9605 const UnaryExprOrTypeTraitExpr *E) {
9606 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +00009607 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +00009608 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00009609 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +00009610 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
9611 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009612 else
Richard Smith6822bd72018-10-26 19:26:45 +00009613 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
9614 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009615 }
Eli Friedman64004332009-03-23 04:38:34 +00009616
Peter Collingbournee190dee2011-03-11 19:24:49 +00009617 case UETT_VecStep: {
9618 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00009619
Peter Collingbournee190dee2011-03-11 19:24:49 +00009620 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00009621 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00009622
Peter Collingbournee190dee2011-03-11 19:24:49 +00009623 // The vec_step built-in functions that take a 3-component
9624 // vector return 4. (OpenCL 1.1 spec 6.11.12)
9625 if (n == 3)
9626 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00009627
Peter Collingbournee190dee2011-03-11 19:24:49 +00009628 return Success(n, E);
9629 } else
9630 return Success(1, E);
9631 }
9632
9633 case UETT_SizeOf: {
9634 QualType SrcTy = E->getTypeOfArgument();
9635 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
9636 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00009637 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
9638 SrcTy = Ref->getPointeeType();
9639
Richard Smithd62306a2011-11-10 06:34:14 +00009640 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00009641 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00009642 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00009643 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009644 }
Alexey Bataev00396512015-07-02 03:40:19 +00009645 case UETT_OpenMPRequiredSimdAlign:
9646 assert(E->isArgumentType());
9647 return Success(
9648 Info.Ctx.toCharUnitsFromBits(
9649 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
9650 .getQuantity(),
9651 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009652 }
9653
9654 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00009655}
9656
Peter Collingbournee9200682011-05-13 03:29:01 +00009657bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009658 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00009659 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00009660 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009661 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00009662 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00009663 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00009664 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00009665 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00009666 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00009667 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00009668 APSInt IdxResult;
9669 if (!EvaluateInteger(Idx, IdxResult, Info))
9670 return false;
9671 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
9672 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009673 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009674 CurrentType = AT->getElementType();
9675 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
9676 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00009677 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00009678 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009679
James Y Knight7281c352015-12-29 22:31:18 +00009680 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00009681 FieldDecl *MemberDecl = ON.getField();
9682 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009683 if (!RT)
9684 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009685 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009686 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00009687 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00009688 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00009689 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00009690 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00009691 CurrentType = MemberDecl->getType().getNonReferenceType();
9692 break;
9693 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009694
James Y Knight7281c352015-12-29 22:31:18 +00009695 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00009696 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00009697
James Y Knight7281c352015-12-29 22:31:18 +00009698 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00009699 CXXBaseSpecifier *BaseSpec = ON.getBase();
9700 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00009701 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009702
9703 // Find the layout of the class whose base we are looking into.
9704 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009705 if (!RT)
9706 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009707 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009708 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00009709 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9710
9711 // Find the base class itself.
9712 CurrentType = BaseSpec->getType();
9713 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
9714 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009715 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +00009716
Douglas Gregord1702062010-04-29 00:18:15 +00009717 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00009718 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00009719 break;
9720 }
Douglas Gregor882211c2010-04-28 22:16:22 +00009721 }
9722 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009723 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009724}
9725
Chris Lattnere13042c2008-07-11 19:10:17 +00009726bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009727 switch (E->getOpcode()) {
9728 default:
9729 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
9730 // See C99 6.6p3.
9731 return Error(E);
9732 case UO_Extension:
9733 // FIXME: Should extension allow i-c-e extension expressions in its scope?
9734 // If so, we could clear the diagnostic ID.
9735 return Visit(E->getSubExpr());
9736 case UO_Plus:
9737 // The result is just the value.
9738 return Visit(E->getSubExpr());
9739 case UO_Minus: {
9740 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +00009741 return false;
9742 if (!Result.isInt()) return Error(E);
9743 const APSInt &Value = Result.getInt();
9744 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
9745 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
9746 E->getType()))
9747 return false;
Richard Smithfe800032012-01-31 04:08:20 +00009748 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009749 }
9750 case UO_Not: {
9751 if (!Visit(E->getSubExpr()))
9752 return false;
9753 if (!Result.isInt()) return Error(E);
9754 return Success(~Result.getInt(), E);
9755 }
9756 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00009757 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00009758 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00009759 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009760 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00009761 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009762 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009763}
Mike Stump11289f42009-09-09 15:08:12 +00009764
Chris Lattner477c4be2008-07-12 01:15:53 +00009765/// HandleCast - This is used to evaluate implicit or explicit casts where the
9766/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00009767bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
9768 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009769 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00009770 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009771
Eli Friedmanc757de22011-03-25 00:43:55 +00009772 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00009773 case CK_BaseToDerived:
9774 case CK_DerivedToBase:
9775 case CK_UncheckedDerivedToBase:
9776 case CK_Dynamic:
9777 case CK_ToUnion:
9778 case CK_ArrayToPointerDecay:
9779 case CK_FunctionToPointerDecay:
9780 case CK_NullToPointer:
9781 case CK_NullToMemberPointer:
9782 case CK_BaseToDerivedMemberPointer:
9783 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00009784 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00009785 case CK_ConstructorConversion:
9786 case CK_IntegralToPointer:
9787 case CK_ToVoid:
9788 case CK_VectorSplat:
9789 case CK_IntegralToFloating:
9790 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009791 case CK_CPointerToObjCPointerCast:
9792 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009793 case CK_AnyPointerToBlockPointerCast:
9794 case CK_ObjCObjectLValueCast:
9795 case CK_FloatingRealToComplex:
9796 case CK_FloatingComplexToReal:
9797 case CK_FloatingComplexCast:
9798 case CK_FloatingComplexToIntegralComplex:
9799 case CK_IntegralRealToComplex:
9800 case CK_IntegralComplexCast:
9801 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00009802 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +00009803 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +00009804 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009805 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009806 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00009807 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +00009808 case CK_IntegralToFixedPoint:
Eli Friedmanc757de22011-03-25 00:43:55 +00009809 llvm_unreachable("invalid cast kind for integral value");
9810
Eli Friedman9faf2f92011-03-25 19:07:11 +00009811 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009812 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009813 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00009814 case CK_ARCProduceObject:
9815 case CK_ARCConsumeObject:
9816 case CK_ARCReclaimReturnedObject:
9817 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009818 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009819 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009820
Richard Smith4ef685b2012-01-17 21:17:26 +00009821 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00009822 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009823 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00009824 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009825 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009826
9827 case CK_MemberPointerToBoolean:
9828 case CK_PointerToBoolean:
9829 case CK_IntegralToBoolean:
9830 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009831 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00009832 case CK_FloatingComplexToBoolean:
9833 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009834 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00009835 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00009836 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00009837 uint64_t IntResult = BoolResult;
9838 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9839 IntResult = (uint64_t)-1;
9840 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009841 }
9842
Leonard Chan8f7caae2019-03-06 00:28:43 +00009843 case CK_FixedPointToIntegral: {
9844 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
9845 if (!EvaluateFixedPoint(SubExpr, Src, Info))
9846 return false;
9847 bool Overflowed;
9848 llvm::APSInt Result = Src.convertToInt(
9849 Info.Ctx.getIntWidth(DestType),
9850 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
9851 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
9852 return false;
9853 return Success(Result, E);
9854 }
9855
Leonard Chanb4ba4672018-10-23 17:55:35 +00009856 case CK_FixedPointToBoolean: {
9857 // Unsigned padding does not affect this.
9858 APValue Val;
9859 if (!Evaluate(Val, Info, SubExpr))
9860 return false;
Leonard Chand3f3e162019-01-18 21:04:25 +00009861 return Success(Val.getFixedPoint().getBoolValue(), E);
Leonard Chanb4ba4672018-10-23 17:55:35 +00009862 }
9863
Eli Friedmanc757de22011-03-25 00:43:55 +00009864 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00009865 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00009866 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00009867
Eli Friedman742421e2009-02-20 01:15:07 +00009868 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009869 // Allow casts of address-of-label differences if they are no-ops
9870 // or narrowing. (The narrowing case isn't actually guaranteed to
9871 // be constant-evaluatable except in some narrow cases which are hard
9872 // to detect here. We let it through on the assumption the user knows
9873 // what they are doing.)
9874 if (Result.isAddrLabelDiff())
9875 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00009876 // Only allow casts of lvalues if they are lossless.
9877 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9878 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009879
Richard Smith911e1422012-01-30 22:27:01 +00009880 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9881 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00009882 }
Mike Stump11289f42009-09-09 15:08:12 +00009883
Eli Friedmanc757de22011-03-25 00:43:55 +00009884 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00009885 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9886
John McCall45d55e42010-05-07 21:00:08 +00009887 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00009888 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009889 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009890
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009891 if (LV.getLValueBase()) {
9892 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009893 // FIXME: Allow a larger integer size than the pointer size, and allow
9894 // narrowing back down to pointer width in subsequent integral casts.
9895 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009896 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009897 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009898
Richard Smithcf74da72011-11-16 07:18:12 +00009899 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009900 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009901 return true;
9902 }
9903
Hans Wennborgdd1ea8a2019-03-06 10:26:19 +00009904 APSInt AsInt;
9905 APValue V;
9906 LV.moveInto(V);
9907 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
9908 llvm_unreachable("Can't cast this!");
Yaxun Liu402804b2016-12-15 08:09:08 +00009909
Richard Smith911e1422012-01-30 22:27:01 +00009910 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009911 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009912
Eli Friedmanc757de22011-03-25 00:43:55 +00009913 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009914 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009915 if (!EvaluateComplex(SubExpr, C, Info))
9916 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009917 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009918 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009919
Eli Friedmanc757de22011-03-25 00:43:55 +00009920 case CK_FloatingToIntegral: {
9921 APFloat F(0.0);
9922 if (!EvaluateFloat(SubExpr, F, Info))
9923 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009924
Richard Smith357362d2011-12-13 06:39:58 +00009925 APSInt Value;
9926 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9927 return false;
9928 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009929 }
9930 }
Mike Stump11289f42009-09-09 15:08:12 +00009931
Eli Friedmanc757de22011-03-25 00:43:55 +00009932 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009933}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009934
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009935bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9936 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009937 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009938 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9939 return false;
9940 if (!LV.isComplexInt())
9941 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009942 return Success(LV.getComplexIntReal(), E);
9943 }
9944
9945 return Visit(E->getSubExpr());
9946}
9947
Eli Friedman4e7a2412009-02-27 04:45:43 +00009948bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009949 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009950 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009951 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9952 return false;
9953 if (!LV.isComplexInt())
9954 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009955 return Success(LV.getComplexIntImag(), E);
9956 }
9957
Richard Smith4a678122011-10-24 18:44:57 +00009958 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009959 return Success(0, E);
9960}
9961
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009962bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9963 return Success(E->getPackLength(), E);
9964}
9965
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009966bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9967 return Success(E->getValue(), E);
9968}
9969
Leonard Chandb01c3a2018-06-20 17:19:40 +00009970bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9971 switch (E->getOpcode()) {
9972 default:
9973 // Invalid unary operators
9974 return Error(E);
9975 case UO_Plus:
9976 // The result is just the value.
9977 return Visit(E->getSubExpr());
9978 case UO_Minus: {
9979 if (!Visit(E->getSubExpr())) return false;
Leonard Chand3f3e162019-01-18 21:04:25 +00009980 if (!Result.isFixedPoint())
9981 return Error(E);
9982 bool Overflowed;
9983 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
9984 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
9985 return false;
9986 return Success(Negated, E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009987 }
9988 case UO_LNot: {
9989 bool bres;
9990 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9991 return false;
9992 return Success(!bres, E);
9993 }
9994 }
9995}
9996
Leonard Chand3f3e162019-01-18 21:04:25 +00009997bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
9998 const Expr *SubExpr = E->getSubExpr();
9999 QualType DestType = E->getType();
10000 assert(DestType->isFixedPointType() &&
10001 "Expected destination type to be a fixed point type");
10002 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
10003
10004 switch (E->getCastKind()) {
10005 case CK_FixedPointCast: {
10006 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
10007 if (!EvaluateFixedPoint(SubExpr, Src, Info))
10008 return false;
10009 bool Overflowed;
10010 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
10011 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
10012 return false;
10013 return Success(Result, E);
10014 }
Leonard Chan8f7caae2019-03-06 00:28:43 +000010015 case CK_IntegralToFixedPoint: {
10016 APSInt Src;
10017 if (!EvaluateInteger(SubExpr, Src, Info))
10018 return false;
10019
10020 bool Overflowed;
10021 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
10022 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
10023
10024 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
10025 return false;
10026
10027 return Success(IntResult, E);
10028 }
Leonard Chand3f3e162019-01-18 21:04:25 +000010029 case CK_NoOp:
10030 case CK_LValueToRValue:
10031 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10032 default:
10033 return Error(E);
10034 }
10035}
10036
10037bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10038 const Expr *LHS = E->getLHS();
10039 const Expr *RHS = E->getRHS();
10040 FixedPointSemantics ResultFXSema =
10041 Info.Ctx.getFixedPointSemantics(E->getType());
10042
10043 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
10044 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
10045 return false;
10046 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
10047 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
10048 return false;
10049
10050 switch (E->getOpcode()) {
10051 case BO_Add: {
10052 bool AddOverflow, ConversionOverflow;
10053 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
10054 .convert(ResultFXSema, &ConversionOverflow);
10055 if ((AddOverflow || ConversionOverflow) &&
10056 !HandleOverflow(Info, E, Result, E->getType()))
10057 return false;
10058 return Success(Result, E);
10059 }
10060 default:
10061 return false;
10062 }
10063 llvm_unreachable("Should've exited before this");
10064}
10065
Chris Lattner05706e882008-07-11 18:11:29 +000010066//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +000010067// Float Evaluation
10068//===----------------------------------------------------------------------===//
10069
10070namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000010071class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010072 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +000010073 APFloat &Result;
10074public:
10075 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +000010076 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +000010077
Richard Smith2e312c82012-03-03 22:46:17 +000010078 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010079 Result = V.getFloat();
10080 return true;
10081 }
Eli Friedman24c01542008-08-22 00:06:13 +000010082
Richard Smithfddd3842011-12-30 21:15:51 +000010083 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +000010084 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
10085 return true;
10086 }
10087
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010088 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +000010089
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010090 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +000010091 bool VisitBinaryOperator(const BinaryOperator *E);
10092 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000010093 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +000010094
John McCallb1fb0d32010-05-07 22:08:54 +000010095 bool VisitUnaryReal(const UnaryOperator *E);
10096 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +000010097
Richard Smithfddd3842011-12-30 21:15:51 +000010098 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +000010099};
10100} // end anonymous namespace
10101
10102static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000010103 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +000010104 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +000010105}
10106
Jay Foad39c79802011-01-12 09:06:06 +000010107static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +000010108 QualType ResultTy,
10109 const Expr *Arg,
10110 bool SNaN,
10111 llvm::APFloat &Result) {
10112 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
10113 if (!S) return false;
10114
10115 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
10116
10117 llvm::APInt fill;
10118
10119 // Treat empty strings as if they were zero.
10120 if (S->getString().empty())
10121 fill = llvm::APInt(32, 0);
10122 else if (S->getString().getAsInteger(0, fill))
10123 return false;
10124
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +000010125 if (Context.getTargetInfo().isNan2008()) {
10126 if (SNaN)
10127 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
10128 else
10129 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
10130 } else {
10131 // Prior to IEEE 754-2008, architectures were allowed to choose whether
10132 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
10133 // a different encoding to what became a standard in 2008, and for pre-
10134 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
10135 // sNaN. This is now known as "legacy NaN" encoding.
10136 if (SNaN)
10137 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
10138 else
10139 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
10140 }
10141
John McCall16291492010-02-28 13:00:19 +000010142 return true;
10143}
10144
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010145bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +000010146 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010147 default:
10148 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10149
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010150 case Builtin::BI__builtin_huge_val:
10151 case Builtin::BI__builtin_huge_valf:
10152 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010153 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010154 case Builtin::BI__builtin_inf:
10155 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010156 case Builtin::BI__builtin_infl:
10157 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +000010158 const llvm::fltSemantics &Sem =
10159 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +000010160 Result = llvm::APFloat::getInf(Sem);
10161 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +000010162 }
Mike Stump11289f42009-09-09 15:08:12 +000010163
John McCall16291492010-02-28 13:00:19 +000010164 case Builtin::BI__builtin_nans:
10165 case Builtin::BI__builtin_nansf:
10166 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010167 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010168 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10169 true, Result))
10170 return Error(E);
10171 return true;
John McCall16291492010-02-28 13:00:19 +000010172
Chris Lattner0b7282e2008-10-06 06:31:58 +000010173 case Builtin::BI__builtin_nan:
10174 case Builtin::BI__builtin_nanf:
10175 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010176 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +000010177 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +000010178 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +000010179 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10180 false, Result))
10181 return Error(E);
10182 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010183
10184 case Builtin::BI__builtin_fabs:
10185 case Builtin::BI__builtin_fabsf:
10186 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010187 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010188 if (!EvaluateFloat(E->getArg(0), Result, Info))
10189 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010190
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010191 if (Result.isNegative())
10192 Result.changeSign();
10193 return true;
10194
Richard Smith8889a3d2013-06-13 06:26:32 +000010195 // FIXME: Builtin::BI__builtin_powi
10196 // FIXME: Builtin::BI__builtin_powif
10197 // FIXME: Builtin::BI__builtin_powil
10198
Mike Stump11289f42009-09-09 15:08:12 +000010199 case Builtin::BI__builtin_copysign:
10200 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010201 case Builtin::BI__builtin_copysignl:
10202 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010203 APFloat RHS(0.);
10204 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
10205 !EvaluateFloat(E->getArg(1), RHS, Info))
10206 return false;
10207 Result.copySign(RHS);
10208 return true;
10209 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010210 }
10211}
10212
John McCallb1fb0d32010-05-07 22:08:54 +000010213bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000010214 if (E->getSubExpr()->getType()->isAnyComplexType()) {
10215 ComplexValue CV;
10216 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10217 return false;
10218 Result = CV.FloatReal;
10219 return true;
10220 }
10221
10222 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +000010223}
10224
10225bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000010226 if (E->getSubExpr()->getType()->isAnyComplexType()) {
10227 ComplexValue CV;
10228 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10229 return false;
10230 Result = CV.FloatImag;
10231 return true;
10232 }
10233
Richard Smith4a678122011-10-24 18:44:57 +000010234 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +000010235 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
10236 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +000010237 return true;
10238}
10239
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010240bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010241 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010242 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000010243 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +000010244 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +000010245 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +000010246 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
10247 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010248 Result.changeSign();
10249 return true;
10250 }
10251}
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010252
Eli Friedman24c01542008-08-22 00:06:13 +000010253bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000010254 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
10255 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +000010256
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010257 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +000010258 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010259 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +000010260 return false;
Richard Smith861b5b52013-05-07 23:34:45 +000010261 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
10262 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +000010263}
10264
10265bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
10266 Result = E->getValue();
10267 return true;
10268}
10269
Peter Collingbournee9200682011-05-13 03:29:01 +000010270bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
10271 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +000010272
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010273 switch (E->getCastKind()) {
10274 default:
Richard Smith11562c52011-10-28 17:51:58 +000010275 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010276
10277 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +000010278 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +000010279 return EvaluateInteger(SubExpr, IntResult, Info) &&
10280 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
10281 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000010282 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010283
10284 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +000010285 if (!Visit(SubExpr))
10286 return false;
Richard Smith357362d2011-12-13 06:39:58 +000010287 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
10288 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000010289 }
John McCalld7646252010-11-14 08:17:51 +000010290
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010291 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +000010292 ComplexValue V;
10293 if (!EvaluateComplex(SubExpr, V, Info))
10294 return false;
10295 Result = V.getComplexFloatReal();
10296 return true;
10297 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010298 }
Eli Friedman9a156e52008-11-12 09:44:48 +000010299}
10300
Eli Friedman24c01542008-08-22 00:06:13 +000010301//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010302// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +000010303//===----------------------------------------------------------------------===//
10304
10305namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000010306class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010307 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000010308 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000010309
Anders Carlsson537969c2008-11-16 20:27:53 +000010310public:
John McCall93d91dc2010-05-07 17:22:02 +000010311 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000010312 : ExprEvaluatorBaseTy(info), Result(Result) {}
10313
Richard Smith2e312c82012-03-03 22:46:17 +000010314 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010315 Result.setFrom(V);
10316 return true;
10317 }
Mike Stump11289f42009-09-09 15:08:12 +000010318
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010319 bool ZeroInitialization(const Expr *E);
10320
Anders Carlsson537969c2008-11-16 20:27:53 +000010321 //===--------------------------------------------------------------------===//
10322 // Visitor Methods
10323 //===--------------------------------------------------------------------===//
10324
Peter Collingbournee9200682011-05-13 03:29:01 +000010325 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000010326 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000010327 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010328 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010329 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010330};
10331} // end anonymous namespace
10332
John McCall93d91dc2010-05-07 17:22:02 +000010333static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
10334 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000010335 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000010336 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010337}
10338
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010339bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000010340 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010341 if (ElemTy->isRealFloatingType()) {
10342 Result.makeComplexFloat();
10343 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
10344 Result.FloatReal = Zero;
10345 Result.FloatImag = Zero;
10346 } else {
10347 Result.makeComplexInt();
10348 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
10349 Result.IntReal = Zero;
10350 Result.IntImag = Zero;
10351 }
10352 return true;
10353}
10354
Peter Collingbournee9200682011-05-13 03:29:01 +000010355bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
10356 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010357
10358 if (SubExpr->getType()->isRealFloatingType()) {
10359 Result.makeComplexFloat();
10360 APFloat &Imag = Result.FloatImag;
10361 if (!EvaluateFloat(SubExpr, Imag, Info))
10362 return false;
10363
10364 Result.FloatReal = APFloat(Imag.getSemantics());
10365 return true;
10366 } else {
10367 assert(SubExpr->getType()->isIntegerType() &&
10368 "Unexpected imaginary literal.");
10369
10370 Result.makeComplexInt();
10371 APSInt &Imag = Result.IntImag;
10372 if (!EvaluateInteger(SubExpr, Imag, Info))
10373 return false;
10374
10375 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
10376 return true;
10377 }
10378}
10379
Peter Collingbournee9200682011-05-13 03:29:01 +000010380bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010381
John McCallfcef3cf2010-12-14 17:51:41 +000010382 switch (E->getCastKind()) {
10383 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010384 case CK_BaseToDerived:
10385 case CK_DerivedToBase:
10386 case CK_UncheckedDerivedToBase:
10387 case CK_Dynamic:
10388 case CK_ToUnion:
10389 case CK_ArrayToPointerDecay:
10390 case CK_FunctionToPointerDecay:
10391 case CK_NullToPointer:
10392 case CK_NullToMemberPointer:
10393 case CK_BaseToDerivedMemberPointer:
10394 case CK_DerivedToBaseMemberPointer:
10395 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000010396 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000010397 case CK_ConstructorConversion:
10398 case CK_IntegralToPointer:
10399 case CK_PointerToIntegral:
10400 case CK_PointerToBoolean:
10401 case CK_ToVoid:
10402 case CK_VectorSplat:
10403 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000010404 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000010405 case CK_IntegralToBoolean:
10406 case CK_IntegralToFloating:
10407 case CK_FloatingToIntegral:
10408 case CK_FloatingToBoolean:
10409 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000010410 case CK_CPointerToObjCPointerCast:
10411 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010412 case CK_AnyPointerToBlockPointerCast:
10413 case CK_ObjCObjectLValueCast:
10414 case CK_FloatingComplexToReal:
10415 case CK_FloatingComplexToBoolean:
10416 case CK_IntegralComplexToReal:
10417 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000010418 case CK_ARCProduceObject:
10419 case CK_ARCConsumeObject:
10420 case CK_ARCReclaimReturnedObject:
10421 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000010422 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000010423 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000010424 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000010425 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000010426 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000010427 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000010428 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000010429 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +000010430 case CK_FixedPointToIntegral:
10431 case CK_IntegralToFixedPoint:
John McCallfcef3cf2010-12-14 17:51:41 +000010432 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000010433
John McCallfcef3cf2010-12-14 17:51:41 +000010434 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010435 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000010436 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +000010437 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010438
10439 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000010440 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010441 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010442 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010443
10444 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010445 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000010446 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010447 return false;
10448
John McCallfcef3cf2010-12-14 17:51:41 +000010449 Result.makeComplexFloat();
10450 Result.FloatImag = APFloat(Real.getSemantics());
10451 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010452 }
10453
John McCallfcef3cf2010-12-14 17:51:41 +000010454 case CK_FloatingComplexCast: {
10455 if (!Visit(E->getSubExpr()))
10456 return false;
10457
10458 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10459 QualType From
10460 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10461
Richard Smith357362d2011-12-13 06:39:58 +000010462 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
10463 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010464 }
10465
10466 case CK_FloatingComplexToIntegralComplex: {
10467 if (!Visit(E->getSubExpr()))
10468 return false;
10469
10470 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10471 QualType From
10472 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10473 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000010474 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
10475 To, Result.IntReal) &&
10476 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
10477 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010478 }
10479
10480 case CK_IntegralRealToComplex: {
10481 APSInt &Real = Result.IntReal;
10482 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
10483 return false;
10484
10485 Result.makeComplexInt();
10486 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
10487 return true;
10488 }
10489
10490 case CK_IntegralComplexCast: {
10491 if (!Visit(E->getSubExpr()))
10492 return false;
10493
10494 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10495 QualType From
10496 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10497
Richard Smith911e1422012-01-30 22:27:01 +000010498 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
10499 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010500 return true;
10501 }
10502
10503 case CK_IntegralComplexToFloatingComplex: {
10504 if (!Visit(E->getSubExpr()))
10505 return false;
10506
Ted Kremenek28831752012-08-23 20:46:57 +000010507 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000010508 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000010509 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000010510 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000010511 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
10512 To, Result.FloatReal) &&
10513 HandleIntToFloatCast(Info, E, From, Result.IntImag,
10514 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010515 }
10516 }
10517
10518 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010519}
10520
John McCall93d91dc2010-05-07 17:22:02 +000010521bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000010522 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000010523 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10524
Chandler Carrutha216cad2014-10-11 00:57:18 +000010525 // Track whether the LHS or RHS is real at the type system level. When this is
10526 // the case we can simplify our evaluation strategy.
10527 bool LHSReal = false, RHSReal = false;
10528
10529 bool LHSOK;
10530 if (E->getLHS()->getType()->isRealFloatingType()) {
10531 LHSReal = true;
10532 APFloat &Real = Result.FloatReal;
10533 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
10534 if (LHSOK) {
10535 Result.makeComplexFloat();
10536 Result.FloatImag = APFloat(Real.getSemantics());
10537 }
10538 } else {
10539 LHSOK = Visit(E->getLHS());
10540 }
George Burgess IVa145e252016-05-25 22:38:36 +000010541 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000010542 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010543
John McCall93d91dc2010-05-07 17:22:02 +000010544 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010545 if (E->getRHS()->getType()->isRealFloatingType()) {
10546 RHSReal = true;
10547 APFloat &Real = RHS.FloatReal;
10548 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
10549 return false;
10550 RHS.makeComplexFloat();
10551 RHS.FloatImag = APFloat(Real.getSemantics());
10552 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000010553 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010554
Chandler Carrutha216cad2014-10-11 00:57:18 +000010555 assert(!(LHSReal && RHSReal) &&
10556 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010557 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010558 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000010559 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010560 if (Result.isComplexFloat()) {
10561 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
10562 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010563 if (LHSReal)
10564 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10565 else if (!RHSReal)
10566 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
10567 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010568 } else {
10569 Result.getComplexIntReal() += RHS.getComplexIntReal();
10570 Result.getComplexIntImag() += RHS.getComplexIntImag();
10571 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010572 break;
John McCalle3027922010-08-25 11:45:40 +000010573 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010574 if (Result.isComplexFloat()) {
10575 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
10576 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010577 if (LHSReal) {
10578 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10579 Result.getComplexFloatImag().changeSign();
10580 } else if (!RHSReal) {
10581 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
10582 APFloat::rmNearestTiesToEven);
10583 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010584 } else {
10585 Result.getComplexIntReal() -= RHS.getComplexIntReal();
10586 Result.getComplexIntImag() -= RHS.getComplexIntImag();
10587 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010588 break;
John McCalle3027922010-08-25 11:45:40 +000010589 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010590 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000010591 // This is an implementation of complex multiplication according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000010592 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000010593 // following naming scheme:
10594 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000010595 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010596 APFloat &A = LHS.getComplexFloatReal();
10597 APFloat &B = LHS.getComplexFloatImag();
10598 APFloat &C = RHS.getComplexFloatReal();
10599 APFloat &D = RHS.getComplexFloatImag();
10600 APFloat &ResR = Result.getComplexFloatReal();
10601 APFloat &ResI = Result.getComplexFloatImag();
10602 if (LHSReal) {
10603 assert(!RHSReal && "Cannot have two real operands for a complex op!");
10604 ResR = A * C;
10605 ResI = A * D;
10606 } else if (RHSReal) {
10607 ResR = C * A;
10608 ResI = C * B;
10609 } else {
10610 // In the fully general case, we need to handle NaNs and infinities
10611 // robustly.
10612 APFloat AC = A * C;
10613 APFloat BD = B * D;
10614 APFloat AD = A * D;
10615 APFloat BC = B * C;
10616 ResR = AC - BD;
10617 ResI = AD + BC;
10618 if (ResR.isNaN() && ResI.isNaN()) {
10619 bool Recalc = false;
10620 if (A.isInfinity() || B.isInfinity()) {
10621 A = APFloat::copySign(
10622 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10623 B = APFloat::copySign(
10624 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10625 if (C.isNaN())
10626 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10627 if (D.isNaN())
10628 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10629 Recalc = true;
10630 }
10631 if (C.isInfinity() || D.isInfinity()) {
10632 C = APFloat::copySign(
10633 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10634 D = APFloat::copySign(
10635 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10636 if (A.isNaN())
10637 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10638 if (B.isNaN())
10639 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10640 Recalc = true;
10641 }
10642 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
10643 AD.isInfinity() || BC.isInfinity())) {
10644 if (A.isNaN())
10645 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10646 if (B.isNaN())
10647 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10648 if (C.isNaN())
10649 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10650 if (D.isNaN())
10651 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10652 Recalc = true;
10653 }
10654 if (Recalc) {
10655 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
10656 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
10657 }
10658 }
10659 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010660 } else {
John McCall93d91dc2010-05-07 17:22:02 +000010661 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000010662 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010663 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
10664 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000010665 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010666 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
10667 LHS.getComplexIntImag() * RHS.getComplexIntReal());
10668 }
10669 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010670 case BO_Div:
10671 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000010672 // This is an implementation of complex division according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000010673 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000010674 // following naming scheme:
10675 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010676 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010677 APFloat &A = LHS.getComplexFloatReal();
10678 APFloat &B = LHS.getComplexFloatImag();
10679 APFloat &C = RHS.getComplexFloatReal();
10680 APFloat &D = RHS.getComplexFloatImag();
10681 APFloat &ResR = Result.getComplexFloatReal();
10682 APFloat &ResI = Result.getComplexFloatImag();
10683 if (RHSReal) {
10684 ResR = A / C;
10685 ResI = B / C;
10686 } else {
10687 if (LHSReal) {
10688 // No real optimizations we can do here, stub out with zero.
10689 B = APFloat::getZero(A.getSemantics());
10690 }
10691 int DenomLogB = 0;
10692 APFloat MaxCD = maxnum(abs(C), abs(D));
10693 if (MaxCD.isFinite()) {
10694 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000010695 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
10696 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010697 }
10698 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000010699 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
10700 APFloat::rmNearestTiesToEven);
10701 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
10702 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010703 if (ResR.isNaN() && ResI.isNaN()) {
10704 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
10705 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
10706 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
10707 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
10708 D.isFinite()) {
10709 A = APFloat::copySign(
10710 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10711 B = APFloat::copySign(
10712 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10713 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
10714 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
10715 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
10716 C = APFloat::copySign(
10717 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10718 D = APFloat::copySign(
10719 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10720 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
10721 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
10722 }
10723 }
10724 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010725 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010726 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
10727 return Error(E, diag::note_expr_divide_by_zero);
10728
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010729 ComplexValue LHS = Result;
10730 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
10731 RHS.getComplexIntImag() * RHS.getComplexIntImag();
10732 Result.getComplexIntReal() =
10733 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
10734 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
10735 Result.getComplexIntImag() =
10736 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
10737 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
10738 }
10739 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010740 }
10741
John McCall93d91dc2010-05-07 17:22:02 +000010742 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010743}
10744
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010745bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10746 // Get the operand value into 'Result'.
10747 if (!Visit(E->getSubExpr()))
10748 return false;
10749
10750 switch (E->getOpcode()) {
10751 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010752 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010753 case UO_Extension:
10754 return true;
10755 case UO_Plus:
10756 // The result is always just the subexpr.
10757 return true;
10758 case UO_Minus:
10759 if (Result.isComplexFloat()) {
10760 Result.getComplexFloatReal().changeSign();
10761 Result.getComplexFloatImag().changeSign();
10762 }
10763 else {
10764 Result.getComplexIntReal() = -Result.getComplexIntReal();
10765 Result.getComplexIntImag() = -Result.getComplexIntImag();
10766 }
10767 return true;
10768 case UO_Not:
10769 if (Result.isComplexFloat())
10770 Result.getComplexFloatImag().changeSign();
10771 else
10772 Result.getComplexIntImag() = -Result.getComplexIntImag();
10773 return true;
10774 }
10775}
10776
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010777bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10778 if (E->getNumInits() == 2) {
10779 if (E->getType()->isComplexType()) {
10780 Result.makeComplexFloat();
10781 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
10782 return false;
10783 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
10784 return false;
10785 } else {
10786 Result.makeComplexInt();
10787 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
10788 return false;
10789 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
10790 return false;
10791 }
10792 return true;
10793 }
10794 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
10795}
10796
Anders Carlsson537969c2008-11-16 20:27:53 +000010797//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000010798// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
10799// implicit conversion.
10800//===----------------------------------------------------------------------===//
10801
10802namespace {
10803class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000010804 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010805 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000010806 APValue &Result;
10807public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010808 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
10809 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000010810
10811 bool Success(const APValue &V, const Expr *E) {
10812 Result = V;
10813 return true;
10814 }
10815
10816 bool ZeroInitialization(const Expr *E) {
10817 ImplicitValueInitExpr VIE(
10818 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010819 // For atomic-qualified class (and array) types in C++, initialize the
10820 // _Atomic-wrapped subobject directly, in-place.
10821 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
10822 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000010823 }
10824
10825 bool VisitCastExpr(const CastExpr *E) {
10826 switch (E->getCastKind()) {
10827 default:
10828 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10829 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010830 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
10831 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000010832 }
10833 }
10834};
10835} // end anonymous namespace
10836
Richard Smith64cb9ca2017-02-22 22:09:50 +000010837static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
10838 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000010839 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010840 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000010841}
10842
10843//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000010844// Void expression evaluation, primarily for a cast to void on the LHS of a
10845// comma operator
10846//===----------------------------------------------------------------------===//
10847
10848namespace {
10849class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010850 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000010851public:
10852 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
10853
Richard Smith2e312c82012-03-03 22:46:17 +000010854 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000010855
Richard Smith7cd577b2017-08-17 19:35:50 +000010856 bool ZeroInitialization(const Expr *E) { return true; }
10857
Richard Smith42d3af92011-12-07 00:43:50 +000010858 bool VisitCastExpr(const CastExpr *E) {
10859 switch (E->getCastKind()) {
10860 default:
10861 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10862 case CK_ToVoid:
10863 VisitIgnoredValue(E->getSubExpr());
10864 return true;
10865 }
10866 }
Hal Finkela8443c32014-07-17 14:49:58 +000010867
10868 bool VisitCallExpr(const CallExpr *E) {
10869 switch (E->getBuiltinCallee()) {
10870 default:
10871 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10872 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000010873 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000010874 // The argument is not evaluated!
10875 return true;
10876 }
10877 }
Richard Smith42d3af92011-12-07 00:43:50 +000010878};
10879} // end anonymous namespace
10880
10881static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
10882 assert(E->isRValue() && E->getType()->isVoidType());
10883 return VoidExprEvaluator(Info).Visit(E);
10884}
10885
10886//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000010887// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000010888//===----------------------------------------------------------------------===//
10889
Richard Smith2e312c82012-03-03 22:46:17 +000010890static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000010891 // In C, function designators are not lvalues, but we evaluate them as if they
10892 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000010893 QualType T = E->getType();
10894 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000010895 LValue LV;
10896 if (!EvaluateLValue(E, LV, Info))
10897 return false;
10898 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010899 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010900 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000010901 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010902 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010903 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010904 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010905 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000010906 LValue LV;
10907 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010908 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010909 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010910 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000010911 llvm::APFloat F(0.0);
10912 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010913 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000010914 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000010915 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000010916 ComplexValue C;
10917 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010918 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010919 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010920 } else if (T->isFixedPointType()) {
10921 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010922 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000010923 MemberPtr P;
10924 if (!EvaluateMemberPointer(E, P, Info))
10925 return false;
10926 P.moveInto(Result);
10927 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000010928 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010929 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010930 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010931 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000010932 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010933 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010934 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010935 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010936 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010937 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000010938 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010939 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010940 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010941 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000010942 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000010943 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000010944 if (!EvaluateVoid(E, Info))
10945 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010946 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010947 QualType Unqual = T.getAtomicUnqualifiedType();
10948 if (Unqual->isArrayType() || Unqual->isRecordType()) {
10949 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010950 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010951 if (!EvaluateAtomic(E, &LV, Value, Info))
10952 return false;
10953 } else {
10954 if (!EvaluateAtomic(E, nullptr, Result, Info))
10955 return false;
10956 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010957 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000010958 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000010959 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010960 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000010961 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000010962 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010963 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010964
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000010965 return true;
10966}
10967
Richard Smithb228a862012-02-15 02:18:13 +000010968/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10969/// cases, the in-place evaluation is essential, since later initializers for
10970/// an object can indirectly refer to subobjects which were initialized earlier.
10971static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000010972 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000010973 assert(!E->isValueDependent());
10974
Richard Smith7525ff62013-05-09 07:14:00 +000010975 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000010976 return false;
10977
10978 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000010979 // Evaluate arrays and record types in-place, so that later initializers can
10980 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000010981 QualType T = E->getType();
10982 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000010983 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010984 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000010985 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010986 else if (T->isAtomicType()) {
10987 QualType Unqual = T.getAtomicUnqualifiedType();
10988 if (Unqual->isArrayType() || Unqual->isRecordType())
10989 return EvaluateAtomic(E, &This, Result, Info);
10990 }
Richard Smithed5165f2011-11-04 05:33:44 +000010991 }
10992
10993 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010994 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010995}
10996
Richard Smithf57d8cb2011-12-09 22:58:01 +000010997/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10998/// lvalue-to-rvalue cast if it is an lvalue.
10999static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000011000 if (E->getType().isNull())
11001 return false;
11002
Nick Lewyckyc190f962017-05-02 01:06:16 +000011003 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000011004 return false;
11005
Richard Smith2e312c82012-03-03 22:46:17 +000011006 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000011007 return false;
11008
11009 if (E->isGLValue()) {
11010 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000011011 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000011012 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000011013 return false;
11014 }
11015
Richard Smith2e312c82012-03-03 22:46:17 +000011016 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000011017 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011018}
Richard Smith11562c52011-10-28 17:51:58 +000011019
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011020static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000011021 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011022 // Fast-path evaluations of integer literals, since we sometimes see files
11023 // containing vast quantities of these.
11024 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
11025 Result.Val = APValue(APSInt(L->getValue(),
11026 L->getType()->isUnsignedIntegerType()));
11027 IsConst = true;
11028 return true;
11029 }
James Dennett0492ef02014-03-14 17:44:10 +000011030
11031 // This case should be rare, but we need to check it before we check on
11032 // the type below.
11033 if (Exp->getType().isNull()) {
11034 IsConst = false;
11035 return true;
11036 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011037
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011038 // FIXME: Evaluating values of large array and record types can cause
11039 // performance problems. Only do so in C++11 for now.
11040 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
11041 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000011042 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011043 IsConst = false;
11044 return true;
11045 }
11046 return false;
11047}
11048
Fangrui Song407659a2018-11-30 23:41:18 +000011049static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
11050 Expr::SideEffectsKind SEK) {
11051 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
11052 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
11053}
11054
11055static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
11056 const ASTContext &Ctx, EvalInfo &Info) {
11057 bool IsConst;
11058 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
11059 return IsConst;
11060
11061 return EvaluateAsRValue(Info, E, Result.Val);
11062}
11063
11064static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
11065 const ASTContext &Ctx,
11066 Expr::SideEffectsKind AllowSideEffects,
11067 EvalInfo &Info) {
11068 if (!E->getType()->isIntegralOrEnumerationType())
11069 return false;
11070
11071 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
11072 !ExprResult.Val.isInt() ||
11073 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11074 return false;
11075
11076 return true;
11077}
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011078
Leonard Chand3f3e162019-01-18 21:04:25 +000011079static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
11080 const ASTContext &Ctx,
11081 Expr::SideEffectsKind AllowSideEffects,
11082 EvalInfo &Info) {
11083 if (!E->getType()->isFixedPointType())
11084 return false;
11085
11086 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
11087 return false;
11088
11089 if (!ExprResult.Val.isFixedPoint() ||
11090 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11091 return false;
11092
11093 return true;
11094}
11095
Richard Smith7b553f12011-10-29 00:50:52 +000011096/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000011097/// any crazy technique (that has nothing to do with language standards) that
11098/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000011099/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
11100/// will be applied to the result.
Fangrui Song407659a2018-11-30 23:41:18 +000011101bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
11102 bool InConstantContext) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000011103 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000011104 Info.InConstantContext = InConstantContext;
11105 return ::EvaluateAsRValue(this, Result, Ctx, Info);
John McCallc07a0c72011-02-17 10:25:35 +000011106}
11107
Jay Foad39c79802011-01-12 09:06:06 +000011108bool Expr::EvaluateAsBooleanCondition(bool &Result,
11109 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000011110 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000011111 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000011112 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000011113}
11114
Fangrui Song407659a2018-11-30 23:41:18 +000011115bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
Richard Smith5fab0c92011-12-28 19:48:30 +000011116 SideEffectsKind AllowSideEffects) const {
Fangrui Song407659a2018-11-30 23:41:18 +000011117 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
11118 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
Richard Smithcaf33902011-10-10 18:28:20 +000011119}
11120
Leonard Chand3f3e162019-01-18 21:04:25 +000011121bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
11122 SideEffectsKind AllowSideEffects) const {
11123 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
11124 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
11125}
11126
Richard Trieube234c32016-04-21 21:04:55 +000011127bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
11128 SideEffectsKind AllowSideEffects) const {
11129 if (!getType()->isRealFloatingType())
11130 return false;
11131
11132 EvalResult ExprResult;
11133 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000011134 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000011135 return false;
11136
11137 Result = ExprResult.Val.getFloat();
11138 return true;
11139}
11140
Jay Foad39c79802011-01-12 09:06:06 +000011141bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000011142 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000011143
John McCall45d55e42010-05-07 21:00:08 +000011144 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000011145 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
11146 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000011147 Ctx.getLValueReferenceType(getType()), LV,
11148 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000011149 return false;
11150
Richard Smith2e312c82012-03-03 22:46:17 +000011151 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000011152 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000011153}
11154
Reid Kleckner1a840d22018-05-10 18:57:35 +000011155bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
11156 const ASTContext &Ctx) const {
11157 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
11158 EvalInfo Info(Ctx, Result, EM);
Eric Fiselier680e8652019-03-08 22:06:48 +000011159 Info.InConstantContext = true;
Eric Fiselieradd16a82019-04-24 02:23:30 +000011160
Reid Kleckner1a840d22018-05-10 18:57:35 +000011161 if (!::Evaluate(Result.Val, Info, this))
11162 return false;
11163
11164 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
11165 Usage);
11166}
11167
Richard Smithd0b4dd62011-12-19 06:19:21 +000011168bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
11169 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011170 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000011171 // FIXME: Evaluating initializers for large array and record types can cause
11172 // performance problems. Only do so in C++11 for now.
11173 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011174 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000011175 return false;
11176
Richard Smithd0b4dd62011-12-19 06:19:21 +000011177 Expr::EvalStatus EStatus;
11178 EStatus.Diag = &Notes;
11179
Richard Smith0c6124b2015-12-03 01:36:22 +000011180 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
11181 ? EvalInfo::EM_ConstantExpression
11182 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000011183 InitInfo.setEvaluatingDecl(VD, Value);
Fangrui Song407659a2018-11-30 23:41:18 +000011184 InitInfo.InConstantContext = true;
Richard Smithd0b4dd62011-12-19 06:19:21 +000011185
11186 LValue LVal;
11187 LVal.set(VD);
11188
Richard Smithfddd3842011-12-30 21:15:51 +000011189 // C++11 [basic.start.init]p2:
11190 // Variables with static storage duration or thread storage duration shall be
11191 // zero-initialized before any other initialization takes place.
11192 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011193 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000011194 !VD->getType()->isReferenceType()) {
11195 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000011196 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000011197 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000011198 return false;
11199 }
11200
Richard Smith7525ff62013-05-09 07:14:00 +000011201 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
11202 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000011203 EStatus.HasSideEffects)
11204 return false;
11205
11206 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
11207 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000011208}
11209
Richard Smith7b553f12011-10-29 00:50:52 +000011210/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
11211/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000011212bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000011213 EvalResult Result;
Fangrui Song407659a2018-11-30 23:41:18 +000011214 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000011215 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000011216}
Anders Carlsson59689ed2008-11-22 21:04:56 +000011217
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000011218APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011219 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Fangrui Song407659a2018-11-30 23:41:18 +000011220 EvalResult EVResult;
11221 EVResult.Diag = Diag;
11222 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
11223 Info.InConstantContext = true;
11224
11225 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000011226 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000011227 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000011228 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000011229
Fangrui Song407659a2018-11-30 23:41:18 +000011230 return EVResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000011231}
John McCall864e3962010-05-07 05:32:02 +000011232
David Bolvansky3b6ae572018-10-18 20:49:06 +000011233APSInt Expr::EvaluateKnownConstIntCheckOverflow(
11234 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Fangrui Song407659a2018-11-30 23:41:18 +000011235 EvalResult EVResult;
11236 EVResult.Diag = Diag;
11237 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11238 Info.InConstantContext = true;
11239
11240 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
David Bolvansky3b6ae572018-10-18 20:49:06 +000011241 (void)Result;
11242 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000011243 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
David Bolvansky3b6ae572018-10-18 20:49:06 +000011244
Fangrui Song407659a2018-11-30 23:41:18 +000011245 return EVResult.Val.getInt();
David Bolvansky3b6ae572018-10-18 20:49:06 +000011246}
11247
Richard Smithe9ff7702013-11-05 22:23:30 +000011248void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011249 bool IsConst;
Fangrui Song407659a2018-11-30 23:41:18 +000011250 EvalResult EVResult;
11251 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
11252 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11253 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011254 }
11255}
11256
Richard Smithe6c01442013-06-05 00:46:14 +000011257bool Expr::EvalResult::isGlobalLValue() const {
11258 assert(Val.isLValue());
11259 return IsGlobalLValue(Val.getLValueBase());
11260}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000011261
11262
John McCall864e3962010-05-07 05:32:02 +000011263/// isIntegerConstantExpr - this recursive routine will test if an expression is
11264/// an integer constant expression.
11265
11266/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
11267/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000011268
11269// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000011270// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
11271// and a (possibly null) SourceLocation indicating the location of the problem.
11272//
John McCall864e3962010-05-07 05:32:02 +000011273// Note that to reduce code duplication, this helper does no evaluation
11274// itself; the caller checks whether the expression is evaluatable, and
11275// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000011276// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000011277
Dan Gohman28ade552010-07-26 21:25:24 +000011278namespace {
11279
Richard Smith9e575da2012-12-28 13:25:52 +000011280enum ICEKind {
11281 /// This expression is an ICE.
11282 IK_ICE,
11283 /// This expression is not an ICE, but if it isn't evaluated, it's
11284 /// a legal subexpression for an ICE. This return value is used to handle
11285 /// the comma operator in C99 mode, and non-constant subexpressions.
11286 IK_ICEIfUnevaluated,
11287 /// This expression is not an ICE, and is not a legal subexpression for one.
11288 IK_NotICE
11289};
11290
John McCall864e3962010-05-07 05:32:02 +000011291struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000011292 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000011293 SourceLocation Loc;
11294
Richard Smith9e575da2012-12-28 13:25:52 +000011295 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000011296};
11297
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011298}
Dan Gohman28ade552010-07-26 21:25:24 +000011299
Richard Smith9e575da2012-12-28 13:25:52 +000011300static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
11301
11302static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000011303
Craig Toppera31a8822013-08-22 07:09:37 +000011304static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000011305 Expr::EvalResult EVResult;
Fangrui Song407659a2018-11-30 23:41:18 +000011306 Expr::EvalStatus Status;
11307 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
11308
11309 Info.InConstantContext = true;
11310 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000011311 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011312 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000011313
John McCall864e3962010-05-07 05:32:02 +000011314 return NoDiag();
11315}
11316
Craig Toppera31a8822013-08-22 07:09:37 +000011317static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000011318 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000011319 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011320 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011321
11322 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000011323#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000011324#define STMT(Node, Base) case Expr::Node##Class:
11325#define EXPR(Node, Base)
11326#include "clang/AST/StmtNodes.inc"
11327 case Expr::PredefinedExprClass:
11328 case Expr::FloatingLiteralClass:
11329 case Expr::ImaginaryLiteralClass:
11330 case Expr::StringLiteralClass:
11331 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011332 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000011333 case Expr::MemberExprClass:
11334 case Expr::CompoundAssignOperatorClass:
11335 case Expr::CompoundLiteralExprClass:
11336 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000011337 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000011338 case Expr::ArrayInitLoopExprClass:
11339 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000011340 case Expr::NoInitExprClass:
11341 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000011342 case Expr::ImplicitValueInitExprClass:
11343 case Expr::ParenListExprClass:
11344 case Expr::VAArgExprClass:
11345 case Expr::AddrLabelExprClass:
11346 case Expr::StmtExprClass:
11347 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000011348 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000011349 case Expr::CXXDynamicCastExprClass:
11350 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000011351 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000011352 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000011353 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000011354 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000011355 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011356 case Expr::CXXThisExprClass:
11357 case Expr::CXXThrowExprClass:
11358 case Expr::CXXNewExprClass:
11359 case Expr::CXXDeleteExprClass:
11360 case Expr::CXXPseudoDestructorExprClass:
11361 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000011362 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000011363 case Expr::DependentScopeDeclRefExprClass:
11364 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000011365 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000011366 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000011367 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000011368 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000011369 case Expr::CXXTemporaryObjectExprClass:
11370 case Expr::CXXUnresolvedConstructExprClass:
11371 case Expr::CXXDependentScopeMemberExprClass:
11372 case Expr::UnresolvedMemberExprClass:
11373 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000011374 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011375 case Expr::ObjCArrayLiteralClass:
11376 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011377 case Expr::ObjCEncodeExprClass:
11378 case Expr::ObjCMessageExprClass:
11379 case Expr::ObjCSelectorExprClass:
11380 case Expr::ObjCProtocolExprClass:
11381 case Expr::ObjCIvarRefExprClass:
11382 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011383 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000011384 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000011385 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000011386 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000011387 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000011388 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000011389 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000011390 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000011391 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000011392 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000011393 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000011394 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000011395 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000011396 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000011397 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000011398 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000011399 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000011400 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011401 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000011402 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011403 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011404 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000011405
Richard Smithf137f932014-01-25 20:50:08 +000011406 case Expr::InitListExprClass: {
11407 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
11408 // form "T x = { a };" is equivalent to "T x = a;".
11409 // Unless we're initializing a reference, T is a scalar as it is known to be
11410 // of integral or enumeration type.
11411 if (E->isRValue())
11412 if (cast<InitListExpr>(E)->getNumInits() == 1)
11413 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011414 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000011415 }
11416
Douglas Gregor820ba7b2011-01-04 17:33:58 +000011417 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000011418 case Expr::GNUNullExprClass:
11419 // GCC considers the GNU __null value to be an integral constant expression.
11420 return NoDiag();
11421
John McCall7c454bb2011-07-15 05:09:51 +000011422 case Expr::SubstNonTypeTemplateParmExprClass:
11423 return
11424 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
11425
Bill Wendling7c44da22018-10-31 03:48:47 +000011426 case Expr::ConstantExprClass:
11427 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
11428
John McCall864e3962010-05-07 05:32:02 +000011429 case Expr::ParenExprClass:
11430 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000011431 case Expr::GenericSelectionExprClass:
11432 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011433 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000011434 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011435 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011436 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000011437 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000011438 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000011439 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000011440 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000011441 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000011442 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000011443 return NoDiag();
11444 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000011445 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000011446 // C99 6.6/3 allows function calls within unevaluated subexpressions of
11447 // constant expressions, but they can never be ICEs because an ICE cannot
11448 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000011449 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000011450 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000011451 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011452 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011453 }
Richard Smith6365c912012-02-24 22:12:32 +000011454 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000011455 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
11456 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000011457 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011458 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000011459 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000011460 // Parameter variables are never constants. Without this check,
11461 // getAnyInitializer() can find a default argument, which leads
11462 // to chaos.
11463 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000011464 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000011465
11466 // C++ 7.1.5.1p2
11467 // A variable of non-volatile const-qualified integral or enumeration
11468 // type initialized by an ICE can be used in ICEs.
11469 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000011470 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000011471 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000011472
Richard Smithd0b4dd62011-12-19 06:19:21 +000011473 const VarDecl *VD;
11474 // Look for a declaration of this variable that has an initializer, and
11475 // check whether it is an ICE.
11476 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
11477 return NoDiag();
11478 else
Richard Smith9e575da2012-12-28 13:25:52 +000011479 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000011480 }
11481 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011482 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000011483 }
John McCall864e3962010-05-07 05:32:02 +000011484 case Expr::UnaryOperatorClass: {
11485 const UnaryOperator *Exp = cast<UnaryOperator>(E);
11486 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000011487 case UO_PostInc:
11488 case UO_PostDec:
11489 case UO_PreInc:
11490 case UO_PreDec:
11491 case UO_AddrOf:
11492 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000011493 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000011494 // C99 6.6/3 allows increment and decrement within unevaluated
11495 // subexpressions of constant expressions, but they can never be ICEs
11496 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011497 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000011498 case UO_Extension:
11499 case UO_LNot:
11500 case UO_Plus:
11501 case UO_Minus:
11502 case UO_Not:
11503 case UO_Real:
11504 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000011505 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011506 }
Reid Klecknere540d972018-11-01 17:51:48 +000011507 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000011508 }
11509 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000011510 // Note that per C99, offsetof must be an ICE. And AFAIK, using
11511 // EvaluateAsRValue matches the proposed gcc behavior for cases like
11512 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
11513 // compliance: we should warn earlier for offsetof expressions with
11514 // array subscripts that aren't ICEs, and if the array subscripts
11515 // are ICEs, the value of the offsetof must be an integer constant.
11516 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000011517 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000011518 case Expr::UnaryExprOrTypeTraitExprClass: {
11519 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
11520 if ((Exp->getKind() == UETT_SizeOf) &&
11521 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011522 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011523 return NoDiag();
11524 }
11525 case Expr::BinaryOperatorClass: {
11526 const BinaryOperator *Exp = cast<BinaryOperator>(E);
11527 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000011528 case BO_PtrMemD:
11529 case BO_PtrMemI:
11530 case BO_Assign:
11531 case BO_MulAssign:
11532 case BO_DivAssign:
11533 case BO_RemAssign:
11534 case BO_AddAssign:
11535 case BO_SubAssign:
11536 case BO_ShlAssign:
11537 case BO_ShrAssign:
11538 case BO_AndAssign:
11539 case BO_XorAssign:
11540 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000011541 // C99 6.6/3 allows assignments within unevaluated subexpressions of
11542 // constant expressions, but they can never be ICEs because an ICE cannot
11543 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011544 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011545
John McCalle3027922010-08-25 11:45:40 +000011546 case BO_Mul:
11547 case BO_Div:
11548 case BO_Rem:
11549 case BO_Add:
11550 case BO_Sub:
11551 case BO_Shl:
11552 case BO_Shr:
11553 case BO_LT:
11554 case BO_GT:
11555 case BO_LE:
11556 case BO_GE:
11557 case BO_EQ:
11558 case BO_NE:
11559 case BO_And:
11560 case BO_Xor:
11561 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011562 case BO_Comma:
11563 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000011564 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11565 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000011566 if (Exp->getOpcode() == BO_Div ||
11567 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000011568 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000011569 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000011570 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000011571 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000011572 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011573 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011574 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000011575 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000011576 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011577 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011578 }
11579 }
11580 }
John McCalle3027922010-08-25 11:45:40 +000011581 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011582 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000011583 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
11584 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000011585 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011586 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011587 } else {
11588 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011589 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011590 }
11591 }
Richard Smith9e575da2012-12-28 13:25:52 +000011592 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000011593 }
John McCalle3027922010-08-25 11:45:40 +000011594 case BO_LAnd:
11595 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000011596 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11597 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011598 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000011599 // Rare case where the RHS has a comma "side-effect"; we need
11600 // to actually check the condition to see whether the side
11601 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000011602 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000011603 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000011604 return RHSResult;
11605 return NoDiag();
11606 }
11607
Richard Smith9e575da2012-12-28 13:25:52 +000011608 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000011609 }
11610 }
Reid Klecknere540d972018-11-01 17:51:48 +000011611 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000011612 }
11613 case Expr::ImplicitCastExprClass:
11614 case Expr::CStyleCastExprClass:
11615 case Expr::CXXFunctionalCastExprClass:
11616 case Expr::CXXStaticCastExprClass:
11617 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000011618 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000011619 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000011620 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000011621 if (isa<ExplicitCastExpr>(E)) {
11622 if (const FloatingLiteral *FL
11623 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
11624 unsigned DestWidth = Ctx.getIntWidth(E->getType());
11625 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
11626 APSInt IgnoredVal(DestWidth, !DestSigned);
11627 bool Ignored;
11628 // If the value does not fit in the destination type, the behavior is
11629 // undefined, so we are not required to treat it as a constant
11630 // expression.
11631 if (FL->getValue().convertToInteger(IgnoredVal,
11632 llvm::APFloat::rmTowardZero,
11633 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011634 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000011635 return NoDiag();
11636 }
11637 }
Eli Friedman76d4e432011-09-29 21:49:34 +000011638 switch (cast<CastExpr>(E)->getCastKind()) {
11639 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011640 case CK_AtomicToNonAtomic:
11641 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000011642 case CK_NoOp:
11643 case CK_IntegralToBoolean:
11644 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000011645 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000011646 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011647 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000011648 }
John McCall864e3962010-05-07 05:32:02 +000011649 }
John McCallc07a0c72011-02-17 10:25:35 +000011650 case Expr::BinaryConditionalOperatorClass: {
11651 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
11652 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011653 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000011654 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011655 if (FalseResult.Kind == IK_NotICE) return FalseResult;
11656 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
11657 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000011658 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000011659 return FalseResult;
11660 }
John McCall864e3962010-05-07 05:32:02 +000011661 case Expr::ConditionalOperatorClass: {
11662 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
11663 // If the condition (ignoring parens) is a __builtin_constant_p call,
11664 // then only the true side is actually considered in an integer constant
11665 // expression, and it is fully evaluated. This is an important GNU
11666 // extension. See GCC PR38377 for discussion.
11667 if (const CallExpr *CallCE
11668 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000011669 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000011670 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000011671 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011672 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011673 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000011674
Richard Smithf57d8cb2011-12-09 22:58:01 +000011675 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
11676 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000011677
Richard Smith9e575da2012-12-28 13:25:52 +000011678 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011679 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011680 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011681 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011682 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000011683 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011684 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000011685 return NoDiag();
11686 // Rare case where the diagnostics depend on which side is evaluated
11687 // Note that if we get here, CondResult is 0, and at least one of
11688 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000011689 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000011690 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000011691 return TrueResult;
11692 }
11693 case Expr::CXXDefaultArgExprClass:
11694 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000011695 case Expr::CXXDefaultInitExprClass:
11696 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011697 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000011698 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011699 }
11700 }
11701
David Blaikiee4d798f2012-01-20 21:50:17 +000011702 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000011703}
11704
Richard Smithf57d8cb2011-12-09 22:58:01 +000011705/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000011706static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000011707 const Expr *E,
11708 llvm::APSInt *Value,
11709 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000011710 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011711 if (Loc) *Loc = E->getExprLoc();
11712 return false;
11713 }
11714
Richard Smith66e05fe2012-01-18 05:21:49 +000011715 APValue Result;
11716 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000011717 return false;
11718
Richard Smith98710fc2014-11-13 23:03:19 +000011719 if (!Result.isInt()) {
11720 if (Loc) *Loc = E->getExprLoc();
11721 return false;
11722 }
11723
Richard Smith66e05fe2012-01-18 05:21:49 +000011724 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000011725 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011726}
11727
Craig Toppera31a8822013-08-22 07:09:37 +000011728bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
11729 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011730 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000011731 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011732
Richard Smith9e575da2012-12-28 13:25:52 +000011733 ICEDiag D = CheckICE(this, Ctx);
11734 if (D.Kind != IK_ICE) {
11735 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000011736 return false;
11737 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000011738 return true;
11739}
11740
Craig Toppera31a8822013-08-22 07:09:37 +000011741bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000011742 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011743 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011744 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
11745
11746 if (!isIntegerConstantExpr(Ctx, Loc))
11747 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000011748
Richard Smith5c40f092015-12-04 03:00:44 +000011749 // The only possible side-effects here are due to UB discovered in the
11750 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
11751 // required to treat the expression as an ICE, so we produce the folded
11752 // value.
Fangrui Song407659a2018-11-30 23:41:18 +000011753 EvalResult ExprResult;
11754 Expr::EvalStatus Status;
11755 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
11756 Info.InConstantContext = true;
11757
11758 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
John McCall864e3962010-05-07 05:32:02 +000011759 llvm_unreachable("ICE cannot be evaluated!");
Fangrui Song407659a2018-11-30 23:41:18 +000011760
11761 Value = ExprResult.Val.getInt();
John McCall864e3962010-05-07 05:32:02 +000011762 return true;
11763}
Richard Smith66e05fe2012-01-18 05:21:49 +000011764
Craig Toppera31a8822013-08-22 07:09:37 +000011765bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000011766 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000011767}
11768
Craig Toppera31a8822013-08-22 07:09:37 +000011769bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000011770 SourceLocation *Loc) const {
11771 // We support this checking in C++98 mode in order to diagnose compatibility
11772 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011773 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000011774
Richard Smith98a0a492012-02-14 21:38:30 +000011775 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000011776 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011777 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000011778 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000011779 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000011780
11781 APValue Scratch;
11782 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
11783
11784 if (!Diags.empty()) {
11785 IsConstExpr = false;
11786 if (Loc) *Loc = Diags[0].first;
11787 } else if (!IsConstExpr) {
11788 // FIXME: This shouldn't happen.
11789 if (Loc) *Loc = getExprLoc();
11790 }
11791
11792 return IsConstExpr;
11793}
Richard Smith253c2a32012-01-27 01:14:48 +000011794
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011795bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
11796 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000011797 ArrayRef<const Expr*> Args,
11798 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011799 Expr::EvalStatus Status;
11800 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000011801 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011802
George Burgess IV177399e2017-01-09 04:12:14 +000011803 LValue ThisVal;
11804 const LValue *ThisPtr = nullptr;
11805 if (This) {
11806#ifndef NDEBUG
11807 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
11808 assert(MD && "Don't provide `this` for non-methods.");
11809 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
11810#endif
11811 if (EvaluateObjectArgument(Info, This, ThisVal))
11812 ThisPtr = &ThisVal;
11813 if (Info.EvalStatus.HasSideEffects)
11814 return false;
11815 }
11816
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011817 ArgVector ArgValues(Args.size());
11818 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
11819 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000011820 if ((*I)->isValueDependent() ||
11821 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011822 // If evaluation fails, throw away the argument entirely.
11823 ArgValues[I - Args.begin()] = APValue();
11824 if (Info.EvalStatus.HasSideEffects)
11825 return false;
11826 }
11827
11828 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000011829 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011830 ArgValues.data());
11831 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
11832}
11833
Richard Smith253c2a32012-01-27 01:14:48 +000011834bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011835 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000011836 PartialDiagnosticAt> &Diags) {
11837 // FIXME: It would be useful to check constexpr function templates, but at the
11838 // moment the constant expression evaluator cannot cope with the non-rigorous
11839 // ASTs which we build for dependent expressions.
11840 if (FD->isDependentContext())
11841 return true;
11842
11843 Expr::EvalStatus Status;
11844 Status.Diag = &Diags;
11845
Richard Smith6d4c6582013-11-05 22:18:15 +000011846 EvalInfo Info(FD->getASTContext(), Status,
11847 EvalInfo::EM_PotentialConstantExpression);
Fangrui Song407659a2018-11-30 23:41:18 +000011848 Info.InConstantContext = true;
Richard Smith253c2a32012-01-27 01:14:48 +000011849
11850 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000011851 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000011852
Richard Smith7525ff62013-05-09 07:14:00 +000011853 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000011854 // is a temporary being used as the 'this' pointer.
11855 LValue This;
11856 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011857 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000011858
Richard Smith253c2a32012-01-27 01:14:48 +000011859 ArrayRef<const Expr*> Args;
11860
Richard Smith2e312c82012-03-03 22:46:17 +000011861 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000011862 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
11863 // Evaluate the call as a constant initializer, to allow the construction
11864 // of objects of non-literal types.
11865 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000011866 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
11867 } else {
11868 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000011869 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000011870 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000011871 }
Richard Smith253c2a32012-01-27 01:14:48 +000011872
11873 return Diags.empty();
11874}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011875
11876bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
11877 const FunctionDecl *FD,
11878 SmallVectorImpl<
11879 PartialDiagnosticAt> &Diags) {
11880 Expr::EvalStatus Status;
11881 Status.Diag = &Diags;
11882
11883 EvalInfo Info(FD->getASTContext(), Status,
11884 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000011885 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011886
11887 // Fabricate a call stack frame to give the arguments a plausible cover story.
11888 ArrayRef<const Expr*> Args;
11889 ArgVector ArgValues(0);
11890 bool Success = EvaluateArgs(Args, ArgValues, Info);
11891 (void)Success;
11892 assert(Success &&
11893 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000011894 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011895
11896 APValue ResultScratch;
11897 Evaluate(ResultScratch, Info, E);
11898 return Diags.empty();
11899}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011900
11901bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
11902 unsigned Type) const {
11903 if (!getType()->isPointerType())
11904 return false;
11905
11906 Expr::EvalStatus Status;
11907 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000011908 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011909}